zink 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.
zink/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+
2
+ from .zink import *
zink/data/__init__.py ADDED
File without changes
Binary file
zink/extractor.py ADDED
@@ -0,0 +1,23 @@
1
+ from gliner import GLiNER
2
+
3
+ class EntityExtractor:
4
+ def __init__(self, model_name="numind/NuNerZero"):
5
+ self.model = GLiNER.from_pretrained(model_name)
6
+ # NuZero requires lower-cased labels.
7
+ self.labels = ["person", "date", "location"]
8
+
9
+ def predict(self, text,labels=None):
10
+ """
11
+ Predict entities in the given text.
12
+ Parameters:
13
+ text (str): The input text.
14
+ labels (list of str, optional): Only entities with these labels will be returned.
15
+ If None, all detected entities are returned.
16
+ Returns:
17
+ list of dict: A list of dictionaries, each containing 'start', 'end', 'label', and 'text'.
18
+ """
19
+ if labels is not None:
20
+ labels = [l.lower() for l in labels]
21
+ else:
22
+ labels = self.labels
23
+ return self.model.predict_entities(text, labels)
zink/merger.py ADDED
@@ -0,0 +1,26 @@
1
+ class EntityMerger:
2
+ def merge(self, entities, text):
3
+ if not entities:
4
+ return []
5
+ merged = []
6
+ current = entities[0].copy()
7
+ current['count'] = 1
8
+
9
+ for next_entity in entities[1:]:
10
+ if (next_entity['label'] == current['label'] and
11
+ (next_entity['start'] == current['end'] or next_entity['start'] == current['end'] + 1)):
12
+ # Merge text from current start to next entity's end
13
+ current['text'] = text[current['start']: next_entity['end']].strip()
14
+ current['end'] = next_entity['end']
15
+ current['score'] = (
16
+ current['score'] * current['count'] + next_entity['score']
17
+ ) / (current['count'] + 1)
18
+ current['count'] += 1
19
+ else:
20
+ current.pop('count', None)
21
+ merged.append(current)
22
+ current = next_entity.copy()
23
+ current['count'] = 1
24
+ current.pop('count', None)
25
+ merged.append(current)
26
+ return merged
@@ -0,0 +1,32 @@
1
+ import csv
2
+ import ahocorasick
3
+ import pickle
4
+
5
+ # File path to the CSV file (adjust as needed)
6
+ input_file = "codes.csv"
7
+
8
+ # Read the CSV file and extract the description column (assumed at index 3)
9
+ descriptions = []
10
+ with open(input_file, newline='', encoding="utf-8") as f:
11
+ reader = csv.reader(f)
12
+ for row in reader:
13
+ # Check that the row has at least 4 columns
14
+ if len(row) >= 4:
15
+ # Strip to remove any surrounding whitespace/quotes
16
+ descriptions.append(row[3].strip())
17
+
18
+ print("Extracted Descriptions:")
19
+ for d in descriptions:
20
+ print(d)
21
+
22
+ # Build the Aho–Corasick automaton with the description strings as patterns
23
+ automaton = ahocorasick.Automaton()
24
+ for desc in descriptions:
25
+ automaton.add_word(desc, desc)
26
+ automaton.make_automaton()
27
+
28
+ # Dump the automaton to a pickle file
29
+ with open("medical_conditions_automaton.pkl", "wb") as out_file:
30
+ pickle.dump(automaton, out_file)
31
+
32
+ print("Automaton built and saved to 'automaton.pkl'")
@@ -0,0 +1,13 @@
1
+ import pickle
2
+
3
+ # Load the saved Aho–Corasick automaton from pickle
4
+ with open("medical_conditions_automaton.pkl", "rb") as f:
5
+ automaton = pickle.load(f)
6
+
7
+ def longest_match(text):
8
+ longest = ""
9
+ # Iterate over all matches in the text using the loaded automaton
10
+ for end_index, word in automaton.iter(text):
11
+ if len(word) > len(longest):
12
+ longest = word
13
+ return longest
@@ -0,0 +1,92 @@
1
+ # anonguard/replacer/__init__.py
2
+
3
+ import random
4
+ from .json_mapping import JsonMappingReplacementStrategy
5
+ from .rdefault import DefaultReplacementStrategy
6
+
7
+
8
+
9
+ class EntityReplacer:
10
+ def __init__(self, use_json_mapping=False):
11
+ """
12
+ user_replacements: Optional dict mapping label -> fixed replacement string or list.
13
+ These override any JSON mapping.
14
+ use_json_mapping: Boolean flag. If True, then for any entity not overridden by
15
+ user_replacements, the JSON mapping is used.
16
+ """
17
+
18
+ self.use_json_mapping = use_json_mapping
19
+
20
+ def replace_entities_ensure_consistency(self, entities, text, user_replacements=None):
21
+ """
22
+ Replace entities in the text with pseudonyms.
23
+ Parameters:
24
+ entities (list of dict): A list of dictionaries, each containing 'start', 'end', 'label', and 'text'.
25
+ text (str): The original text.
26
+ user_replacements (dict, optional): A dictionary of user-defined replacements for specific entity labels.
27
+ If provided, these will override the JSON-based mappings.
28
+ Returns:
29
+ str: The text with entities replaced by pseudonyms.
30
+ 1. If user_replacements is provided, it overrides any JSON mapping.
31
+ 2. If use_json_mapping is True, JSON mapping is used for entities not in user_replacements.
32
+ 3. Otherwise, DefaultReplacementStrategy is used.
33
+ 4. If no entities are found, the original text is returned.
34
+ """
35
+ self.user_replacements = {}
36
+ if user_replacements:
37
+ for label, replacement in user_replacements.items():
38
+ self.user_replacements[label.lower()] = replacement
39
+
40
+ new_text = ""
41
+ last_index = 0
42
+ replacements = {}
43
+ for ent in entities:
44
+ if ent['text'] not in replacements.keys():
45
+ label = ent['label'].lower()
46
+ if label in self.user_replacements:
47
+ fixed = self.user_replacements[label]
48
+ if isinstance(fixed, list):
49
+ replacement = random.choice(fixed)
50
+ else:
51
+ replacement = fixed
52
+ elif self.use_json_mapping:
53
+ replacement = JsonMappingReplacementStrategy(label).replace(ent)
54
+ else:
55
+ replacement = DefaultReplacementStrategy().replace(ent)
56
+ replacements[ent['text']] = replacement
57
+ for key, value in replacements.items():
58
+ text = text.replace(key, value)
59
+ return text
60
+
61
+ def replace_entities(self, entities, text, user_replacements=None):
62
+ """
63
+ """
64
+ self.user_replacements = {}
65
+ if user_replacements:
66
+ for label, replacement in user_replacements.items():
67
+ self.user_replacements[label.lower()] = replacement
68
+
69
+ new_text = ""
70
+ last_index = 0
71
+
72
+ for entity in entities:
73
+ #if entity not in replacement_found
74
+ new_text += text[last_index:entity['start']]
75
+ label = entity['label'].lower()
76
+ replacement = None
77
+
78
+ # Priority: user replacement > JSON mapping (if enabled) > default
79
+ if label in self.user_replacements:
80
+ fixed = self.user_replacements[label]
81
+ if isinstance(fixed, list):
82
+ replacement = random.choice(fixed)
83
+ else:
84
+ replacement = fixed
85
+ elif self.use_json_mapping:
86
+ replacement = JsonMappingReplacementStrategy(label).replace(entity)
87
+ else:
88
+ replacement = DefaultReplacementStrategy().replace(entity)
89
+ new_text += replacement
90
+ last_index = entity['end']
91
+ new_text += text[last_index:]
92
+ return new_text
zink/replacer/base.py ADDED
@@ -0,0 +1,5 @@
1
+ class ReplacementStrategy:
2
+ def replace(self, entity):
3
+ """Return a pseudonym for the given entity.
4
+ This method should be overridden by subclasses."""
5
+ raise NotImplementedError
zink/replacer/fixed.py ADDED
@@ -0,0 +1,15 @@
1
+
2
+ import random
3
+ from .base import ReplacementStrategy
4
+
5
+ class FixedReplacementStrategy(ReplacementStrategy):
6
+ def __init__(self, fixed_value):
7
+ # If the user provides a single string, wrap it in a list.
8
+ if isinstance(fixed_value, list):
9
+ self.fixed_values = fixed_value
10
+ else:
11
+ self.fixed_values = [fixed_value]
12
+
13
+ def replace(self, entity):
14
+ return random.choice(self.fixed_values)
15
+
@@ -0,0 +1,68 @@
1
+ import json
2
+ import random
3
+ import gzip
4
+ import shutil
5
+ from pathlib import Path
6
+ import importlib.resources as resources # available in Python 3.7+
7
+ from .base import ReplacementStrategy
8
+
9
+ def ensure_replacements_json():
10
+ """
11
+ Ensure that the decompressed replacements.json file exists in a writable cache.
12
+ If it doesn't exist, decompress it from the bundled gzip file.
13
+ Returns the path to the JSON file.
14
+ """
15
+ # Define a cache directory (e.g., in the user's home directory)
16
+ cache_dir = Path.home() / ".cache" / "zink"
17
+ cache_dir.mkdir(parents=True, exist_ok=True)
18
+
19
+ json_path = cache_dir / "replacements.json"
20
+
21
+ if not json_path.exists():
22
+ try:
23
+ # Open the compressed file from the package resources.
24
+ # Make sure that the 'zink.data' subpackage has an __init__.py.
25
+ with resources.files("zink.data").joinpath("replacements.json.gzip").open("rb") as gz_file:
26
+ with gzip.open(gz_file, "rb") as f_in:
27
+ with open(json_path, "wb") as f_out:
28
+ shutil.copyfileobj(f_in, f_out)
29
+
30
+ print(f"Decompressed gzip to {json_path}")
31
+ except Exception as e:
32
+ print(f"Error decompressing gzip file: {e}")
33
+ else:
34
+ print(f"{json_path} already exists.")
35
+
36
+ return json_path
37
+
38
+ def load_mapping():
39
+ """
40
+ Load the JSON mapping, ensuring the decompressed JSON file exists.
41
+ """
42
+ json_path = ensure_replacements_json()
43
+ try:
44
+ with open(json_path, "r") as f:
45
+ return json.load(f)
46
+ except Exception as e:
47
+ print(f"Error loading JSON mapping: {e}")
48
+ return {}
49
+
50
+ # Load mapping globally so it is loaded only once.
51
+ GLOBAL_MAPPING = load_mapping()
52
+
53
+ class JsonMappingReplacementStrategy(ReplacementStrategy):
54
+ def __init__(self, label):
55
+ # Store the label in lowercase.
56
+ self.label = label.lower()
57
+
58
+ def replace(self, entity):
59
+ candidates = GLOBAL_MAPPING.get(self.label)
60
+ if candidates and isinstance(candidates, list):
61
+ first_random = random.choice(candidates)
62
+ if first_random != entity['text']:
63
+ return first_random
64
+ second_random = random.choice(candidates)
65
+ if second_random != entity['text']:
66
+ return second_random
67
+ return "[REDACTED]"
68
+ return "[REDACTED]"
zink/replacer/rdate.py ADDED
@@ -0,0 +1,14 @@
1
+ from datetime import datetime, timedelta
2
+ import random
3
+ from .base import ReplacementStrategy
4
+
5
+ class DateReplacementStrategy(ReplacementStrategy):
6
+ def __init__(self, start_date=datetime(1900,1,1), end_date=datetime(2100,12,31)):
7
+ self.start_date = start_date
8
+ self.end_date = end_date
9
+
10
+ def replace(self, entity):
11
+ delta = self.end_date - self.start_date
12
+ random_days = random.randint(0, delta.days)
13
+ random_date = self.start_date + timedelta(days=random_days)
14
+ return random_date.strftime("%Y-%m-%d")
@@ -0,0 +1,5 @@
1
+ from .base import ReplacementStrategy
2
+
3
+ class DefaultReplacementStrategy(ReplacementStrategy):
4
+ def replace(self, entity):
5
+ return "[REDACTED]"
@@ -0,0 +1,11 @@
1
+ from .base import ReplacementStrategy
2
+ import random
3
+
4
+ class PersonReplacementStrategy(ReplacementStrategy):
5
+ def __init__(self, pseudonyms=None):
6
+ if pseudonyms is None:
7
+ pseudonyms = ["Alice", "Bob", "Charlie", "Diana"]
8
+ self.pseudonyms = pseudonyms
9
+
10
+ def replace(self, entity):
11
+ return random.choice(self.pseudonyms)
zink/result.py ADDED
@@ -0,0 +1,18 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import List, Dict
3
+
4
+ @dataclass
5
+ class ReplacementDetail:
6
+ label: str
7
+ original: str
8
+ pseudonym: str
9
+ start: int
10
+ end: int
11
+ score: float # average confidence, etc.
12
+
13
+ @dataclass
14
+ class PseudonymizationResult:
15
+ original_text: str
16
+ anonymized_text: str
17
+ replacements: List[ReplacementDetail] = field(default_factory=list)
18
+ features: Dict = field(default_factory=dict)
zink/tests/__init__.py ADDED
File without changes
@@ -0,0 +1,30 @@
1
+ import sys
2
+ import os
3
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
4
+ import pytest
5
+ import zink as pss
6
+
7
+ def test01():
8
+ text = "John works as a doctor and plays football after work and drives a toyota."
9
+ labels = ("person","profession","sport","car")
10
+ q = pss.redact(text, labels)
11
+ assert "John" not in q.anonymized_text and "doctor" not in q.anonymized_text and "football" not in q.anonymized_text and "toyota" not in q.anonymized_text
12
+
13
+ def test02():
14
+ text = "Samantha is sitting on a french chair"
15
+ labels = ("person","furniture")
16
+ q = pss.redact(text, labels)
17
+ print(q.anonymized_text)
18
+ assert "person_REDACTED" in q.anonymized_text and "furniture_REDACTED" in q.anonymized_text
19
+
20
+ def test03():
21
+ text = "Patient, 33 years old, was admitted with a chest pain"
22
+ labels = ("age","medical condition")
23
+ q = pss.replace(text, labels)
24
+ assert "33 years old" not in q.anonymized_text and "chest pain" not in q.anonymized_text
25
+
26
+ def test04():
27
+ text = "John Doe dialled his mother at 992-234-3456 and then went out for a walk."
28
+ labels = ("person","phone number","relationship")
29
+ q = pss.replace(text, labels)
30
+ assert "John Doe" not in q.anonymized_text and "992-234-3456" not in q.anonymized_text and "mother" not in q.anonymized_text
zink/utils/__init__.py ADDED
File without changes
@@ -0,0 +1,37 @@
1
+ import gzip
2
+ import shutil
3
+ import sys
4
+ import os
5
+ from pathlib import Path
6
+ import importlib.resources as resources
7
+
8
+ def compress_file(input_file, output_file):
9
+ """Compress the input_file and save it as output_file using gzip."""
10
+ with open(input_file, 'rb') as f_in, gzip.open(output_file, 'wb') as f_out:
11
+ shutil.copyfileobj(f_in, f_out)
12
+ print(f"Compressed '{input_file}' to '{output_file}'.")
13
+
14
+ def decompress_file(input_file, output_file):
15
+ """Decompress the input_file and save the result as output_file."""
16
+ with gzip.open(input_file, 'rb') as f_in, open(output_file, 'wb') as f_out:
17
+ shutil.copyfileobj(f_in, f_out)
18
+ print(f"Success : Decompressed '{input_file}' to '{output_file}'.")
19
+
20
+ def ensure_replacements_json():
21
+ cache_dir = Path.home() / ".cache" / "zink"
22
+ cache_dir.mkdir(parents=True, exist_ok=True)
23
+
24
+ json_path = cache_dir / "replacements.json"
25
+
26
+ if not json_path.exists():
27
+ with resources.open_binary("zink.data", "replacements.json.gz") as gz_file:
28
+ with gzip.open(gz_file, "rb") as f_in:
29
+ with open(json_path, "wb") as f_out:
30
+ shutil.copyfileobj(f_in, f_out)
31
+ print(f"Decompressed gzip to {json_path}")
32
+ else:
33
+ print(f"{json_path} already exists.")
34
+
35
+ return json_path
36
+
37
+
zink/zink.py ADDED
@@ -0,0 +1,138 @@
1
+ from .extractor import EntityExtractor
2
+ from .merger import EntityMerger
3
+ from .replacer import EntityReplacer
4
+ from .result import PseudonymizationResult # Assume you defined this dataclass
5
+ import warnings
6
+ warnings.filterwarnings("ignore")
7
+ from functools import lru_cache
8
+ # Instantiate default components at module load time.
9
+
10
+ _DEFAULT_EXTRACTOR = EntityExtractor()
11
+ _DEFAULT_MERGER = EntityMerger()
12
+
13
+
14
+ class Pseudonymizer:
15
+ """
16
+ A class for pseudonymizing text by replacing sensitive entities with non-sensitive placeholders.
17
+ This class provides methods to extract entities, merge adjacent entities, and replace them with pseudonyms.
18
+ It supports custom user-defined replacements and JSON-based mappings for entity replacement.
19
+ Parameters:
20
+ user_replacements (dict, optional): A dictionary of user-defined replacements for specific entity labels.
21
+ If provided, these will override the JSON-based mappings.
22
+ use_json_mapping (bool, optional): If True, use JSON-based mappings for entity replacement.
23
+ If False, only use user-defined replacements.
24
+ extractor (EntityExtractor, optional): An instance of EntityExtractor for extracting entities from text.
25
+ If None, a default extractor will be used.
26
+ merger (EntityMerger, optional): An instance of EntityMerger for merging adjacent entities.
27
+ If None, a default merger will be used.
28
+ replacer (EntityReplacer, optional): An instance of EntityReplacer for replacing entities with pseudonyms.
29
+ If None, a default replacer will be used.
30
+ text (str): The input text to be pseudonymized.
31
+ """
32
+ def __init__(self, use_json_mapping=True,
33
+ extractor=None, merger=None, replacer=None):
34
+ # 'labels' can be used by the extractor if needed.
35
+ self.extractor = extractor if extractor is not None else _DEFAULT_EXTRACTOR
36
+ self.merger = merger if merger is not None else _DEFAULT_MERGER
37
+ self.replacer = (replacer if replacer is not None
38
+ else EntityReplacer(use_json_mapping=use_json_mapping))
39
+ self.text = ""
40
+
41
+ @lru_cache()
42
+ def redact(self, text = "",categories=None,placeholder=None):
43
+ """
44
+ Find and Redact categories in given text.
45
+ Parameters:
46
+ text (str): The input text.
47
+ categories (tuple of str, optional): Only entities with these labels will be anonymized.
48
+ If None, ["person", "date", "location"] are anonymized.
49
+ """
50
+ # Step 1: Extract entities and merge adjacent ones.
51
+ self.text = text
52
+ entities = self.extractor.predict(self.text, labels = categories)
53
+
54
+ self.merged_entities = self.merger.merge(entities, self.text)
55
+
56
+ # If categories are provided, filter to only include those entities.
57
+ if categories is not None:
58
+ categories = [c.lower() for c in categories]
59
+ self.merged_entities = [e for e in self.merged_entities if e['label'].lower() in categories]
60
+ pseudonymized_text = self.text
61
+ for ent in self.merged_entities:
62
+ if placeholder is None:
63
+ placeholder_ = f"{ent['label']}_REDACTED"
64
+ #print(f"Replacing {ent['text']} with {placeholder_}")
65
+ pseudonymized_text = pseudonymized_text.replace(ent['text'], placeholder_)
66
+
67
+ # Build and return a structured result.
68
+ return PseudonymizationResult(
69
+ original_text=self.text,
70
+ anonymized_text=pseudonymized_text,
71
+ replacements=self.merged_entities, # Additional details if needed.
72
+ features={"num_replacements": len(self.merged_entities)}
73
+ )
74
+
75
+ @lru_cache()
76
+ def replace(self, text = "",categories=None, user_replacements=None, ensure_consistency=True):
77
+ """
78
+ Find and Replace categories in given text.
79
+
80
+ Parameters:
81
+ text (str): The input text.
82
+ categories (tuple of str, optional): Only entities with these labels will be anonymized.
83
+ If None, all detected entities are anonymized.
84
+ user_replacements (dict, optional): A dictionary of user-defined replacements for specific entity labels.
85
+ If provided, these will override the JSON-based mappings.
86
+
87
+ Returns:
88
+ PseudonymizationResult: A structured result with original text, pseudonymized text, etc.
89
+ """
90
+ self.text = text
91
+ # Step 1: Extract entities and merge adjacent ones.
92
+ entities = self.extractor.predict(self.text, labels = categories)
93
+ self.merged_entities = self.merger.merge(entities, self.text)
94
+
95
+ # If categories are provided, filter to only include those entities.
96
+ if categories is not None:
97
+ categories = [c.lower() for c in categories]
98
+ self.merged_entities = [e for e in self.merged_entities if e['label'].lower() in categories]
99
+
100
+ # Step 2: Replace entities.
101
+ if ensure_consistency:
102
+ # Ensure consistency in replacements.
103
+ pseudonymized_text = self.replacer.replace_entities_ensure_consistency(self.merged_entities, self.text, user_replacements)
104
+ else:
105
+ # Use the default replacement strategy.
106
+ pseudonymized_text = self.replacer.replace_entities(self.merged_entities, self.text, user_replacements)
107
+
108
+ # Build and return a structured result.
109
+ return PseudonymizationResult(
110
+ original_text=self.text,
111
+ anonymized_text=pseudonymized_text,
112
+ replacements=self.merged_entities, # Additional details if needed.
113
+ features={"num_replacements": len(self.merged_entities)}
114
+ )
115
+
116
+
117
+
118
+ # For usage enhancement:
119
+
120
+ _default_instance = Pseudonymizer()
121
+
122
+ @lru_cache()
123
+ def replace(text, categories=None, user_replacements=None, ensure_consistency=True):
124
+ return _default_instance.replace(
125
+ text=text,
126
+ categories=categories,
127
+ user_replacements=user_replacements,
128
+ ensure_consistency=ensure_consistency
129
+ )
130
+
131
+ @lru_cache()
132
+ def redact(text, categories=None, placeholder=None):
133
+ return _default_instance.redact(
134
+ text=text,
135
+ categories=categories,
136
+ placeholder=placeholder
137
+ )
138
+ # This allows users to call `replace` and `redact` directly without needing to instantiate the class.
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: zink
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: gliner>=0.2.16
8
+ Requires-Dist: pyahocorasick>=2.1.0
9
+ Requires-Dist: spacy>=3.8.4
10
+ Description-Content-Type: text/markdown
11
+
12
+ # ZINK (Zero-shot Ink)
13
+
14
+ ZINK is a Python package designed for zero-shot anonymization of entities within unstructured text data. It allows you to redact or replace sensitive information based on specified entity labels.
15
+
16
+ ## Description
17
+
18
+ In today's data-driven world, protecting sensitive information is paramount. ZINK provides a simple and effective solution for anonymizing text data by identifying and masking entities such as names, ages, phone numbers, medical conditions, and more. With ZINK, you can ensure data privacy while still maintaining the utility of your text data for analysis and processing.
19
+
20
+ ZINK leverages the power of zero-shot techniques, meaning it doesn't require prior training on specific datasets. You simply provide the text and the entity labels you want to anonymize, and ZINK handles the rest.
21
+
22
+ ## Features
23
+
24
+ - **Zero-shot anonymization:** No training data or pre-trained models required.
25
+ - **Flexible entity labeling:** Anonymize any type of entity by specifying custom labels.
26
+ - **Redaction and replacement:** Choose between redacting entities (replacing them with `[LABEL]_REDACTED`) or replacing them with a generic placeholder.
27
+ - **Easy integration:** Simple and intuitive API for seamless integration into your Python projects.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install zink
33
+ ```
34
+ ## Usage
35
+
36
+ ### Redacting Entities
37
+ The redact function replaces identified entities with [LABEL]_REDACTED.
38
+
39
+ ```bash
40
+ Python
41
+
42
+ import zink as pss
43
+
44
+ text = "John works as a doctor and plays football after work and drives a toyota."
45
+ labels = ("person", "profession", "sport", "car")
46
+ result = pss.redact(text, labels)
47
+ print(result.anonymized_text)
48
+ Example output:
49
+
50
+ person_REDACTED works as a profession_REDACTED and plays sport_REDACTED after work and drives a car_REDACTED.
51
+ ```
52
+
53
+ ### Replacing Entities
54
+ The replace function replaces identified entities with a random entity of the same type.
55
+
56
+ ```bash
57
+ Python
58
+
59
+ import zink as pss
60
+
61
+ text = "John Doe dialled his mother at 992-234-3456 and then went out for a walk."
62
+ labels = ("person", "phone number", "relationship")
63
+ result = pss.replace(text, labels)
64
+ print(result.anonymized_text)
65
+ Example output:
66
+
67
+ Warren Buffet dialled his Uncle at 2347789287 and then went out for a walk.
68
+ ```
69
+
70
+ Another example:
71
+
72
+ ```bash
73
+ Python
74
+
75
+ import zink as pss
76
+
77
+ text = "Patient, 33 years old, was admitted with a chest pain"
78
+ labels = ("age", "medical condition")
79
+ result = pss.replace(text, labels)
80
+ print(result.anonymized_text)
81
+ Example output:
82
+
83
+ Patient, 78 years old, was admitted with a Diabetes Mellitus.
84
+ ```
85
+
86
+ ### Testing
87
+ To run the tests, navigate to the project directory and execute:
88
+
89
+ ```bash
90
+ pytest
91
+ ```
92
+
93
+ ### Contributing
94
+ Contributions are welcome! Please feel free to submit pull requests or open issues to suggest improvements or report bugs.  
95
+
96
+ Fork the repository.
97
+ Create a new branch: git checkout -b feature/your-feature
98
+ Make your changes.
99
+ Commit your changes: git commit -m 'Add your feature'
100
+ Push to the branch: git push origin feature/your-feature
101
+ Submit a pull request.
102
+ License
103
+ This project is licensed under the Apache 2.0 License.
@@ -0,0 +1,24 @@
1
+ zink/__init__.py,sha256=f9jCmmae-e1HSZ0cHf7Cy_iI-Eoj1xhOGF6NsLhcMzM,20
2
+ zink/extractor.py,sha256=HruaAqbBO7vAgK_8QnxtkzwhoZ8I6NfXOAni42U0kwc,888
3
+ zink/merger.py,sha256=9Ka7iuw6Sdzeqz2bB8aitMgcf_U2t_2vKdVxGLdS7Fk,1072
4
+ zink/result.py,sha256=nLSGAUVmGeyP7N07l5A5KlRH-JAy3pow7KSCh6yxT_U,444
5
+ zink/zink.py,sha256=8svCcv_0Gr9Ir3fFZ6GTNuwpxKG7QbLDxkaNsbQugBk,6397
6
+ zink/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ zink/data/replacements.json.gzip,sha256=-EKUudGPzkKXhZYV7kaIbDW9lvjm2OGnx9wUjiD7GL0,24322003
8
+ zink/misc/create_automaton.py,sha256=XvWdDXUj0dkpkDDBO7JHDnJgjNNGJWVV7hsKI-u9kAA,979
9
+ zink/misc/fast_search.py,sha256=GjXjmu0yg8lFBIwvw_S-LMFDV8_FM0RJz1h4gmm8F2w,403
10
+ zink/replacer/__init__.py,sha256=UoFoUFaHoUDiTYTKjEOp0iIL5Zxrsv21FrCReXc0mnY,3887
11
+ zink/replacer/base.py,sha256=icGJy_cvZDvV0RQWuMSFA6oWQ2gVGDhCt3XRRkny0hI,202
12
+ zink/replacer/fixed.py,sha256=LDG_pNHvdvVtBUDV89jSEx0tTWfKdZUYteT22UkzsH0,438
13
+ zink/replacer/json_mapping.py,sha256=5QPk9E8LH2UgmLoEtOOTPPoMF8RSSFs5OgpL9aCS02k,2382
14
+ zink/replacer/rdate.py,sha256=1o65sNTveSXruCKcVxeTNKLkYICkvSBaxyTbkKun2u8,549
15
+ zink/replacer/rdefault.py,sha256=wEoL7lPm02NOmgmuvTwgQXGM4INx7BIE8LXN1ljIksM,152
16
+ zink/replacer/rperson.py,sha256=AbF7I7KF63Y2s5SALdU4rzS-hG2J7y-_o0foRArcr6k,355
17
+ zink/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ zink/tests/test_basic.py,sha256=YHr1Y1vU_FgYQfiy0SeuLxoR03sQVxFxkKo2HpEqSy4,1315
19
+ zink/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ zink/utils/data_utils.py,sha256=9iqxdhARv2mpszdQEiBygmojIBY7D_kFncMLIkcWW-s,1315
21
+ zink-0.1.0.dist-info/METADATA,sha256=JW2PEKWvWpCZABqniMXz0po5Gp-rUiKFpZHJ4iNzFiI,3342
22
+ zink-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
23
+ zink-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
24
+ zink-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.