GithubHelp home page GithubHelp logo

statcan / canonym Goto Github PK

View Code? Open in Web Editor NEW
5.0 1.0 0.0 129 KB

Canonym - Anonymization Package

Home Page: https://github.com/StatCan/Canonym

License: MIT License

Jupyter Notebook 20.15% Python 79.85%
anonymization presidio privacy-protection private-information-retrieval

canonym's Introduction

Le français suit l'anglais

Canonym - Anonymization Package

Installation

Create a virtual environment with Python >=3.9 .. code:

conda create -n=canonym python=3.9
conda activate canonym

You can install Canonym using the wheel located in the dist folder:

pip install dist\canonym_public-2023.9.15-py3-none-any.whl

Usage

Basic usage

from canonym import Canonym

anonymizer = Canonym()

text = "This is John Doe, from Ottawa, his phone number is 123-456-7890"
anonymizer.anonymize(text)

Canonym can accept as an input the following :

  • string
  • list of strings
  • Textitem object
  • Pandas Series
  • Pandas DataFrame

You can use directly the anonymize() method, or use the input specific methods :

  • str: anonymizer.anonymize_text,
  • TextItem: anonymizer.anonymize_text,
  • list: anonymizer.anonymize_list,
  • DataFrame: anonymizer.anonymize_dataframe,
  • Series: anonymizer.anonymize_pd_series

Strategies

The following default are available by default:

  • replace_all_with_tag : replaces all entities with their Entity Type
  • redact_all : redacts all PI
  • hash_all : Hashes the PI entities
  • mask_all : Masks all DEFAULT entities
  • scramble_all : Scrambles (changes the order of letters) for all entities
  • mixed_per_entity_type : {hash : ALPHABET_ENTITIES, mask : SPECIAL_ENTITIES, randomize : NUMERIC_ENTITIES, redact : ALPHANUMERIC_ENTITIES}
  • hash_one : {hash: [PERSON]}
  • mask_some: {mask: [PERSON, FULL_ADDRESS], redact: [PHONE_NUMBER]}
  • replace_custom: {replace: CUSTOM_ENTITIES}
  • redact_custom: {redact : CUSTOM_ENTITIES}
  • faker_custom: {faker : CUSTOM_ENTITIES}
  • faker_all: {faker : DEFAULT_ENTITIES}
  • replace_w_value_custom: {replace_val : CUSTOM_ENTITIES}

By default the anonymize method will use the replace_all_with_tag strategy, to use a different strategy use :

   anonymizer.anonymize(text, strategy='redact_all')

Language

The language parameter provides the language of the text, defaults to english, if None or "auto" are provided a search will be conducted to automatically find the right language for each text input. By default Canonym handles English and French text.

In the case of a Pandas DataFrame, also accepts a dict of format {column_name:language or auto, }, so each column can be set to a different language or to automatic search.

# a string
anonymizer.anonymize(text, strategy='redact_all', language='fr')
# a Pandas DataFrame
anonymizer.anonymize(df, language={'column1': 'en', 'column2': 'fr', 'column3': 'auto'} )

Advanced Configuration

The behavior of Canonym can be modified, by editing the two configuration files :

  • ner_config_default.yaml
  • anonymizer_config_default.yaml

in ner_config_default.yaml the following can be defined :

  • AVAILABLE_LANGS : Which language Canonym can handle, defaults to en and fr

  • SCORE_THRESHOLD : The confidence score threshold over which an entity is tagged, defaults at 0.4

  • DEFAULT_RECOGNIZERS : List of recognizers loaded by Canonym

  • POST_PROCESSING_ENTITIES : Entity specific post-processing

  • PRESIDIO_NLP_ENGINE_CONFIG : Some entities will be handled by a spacy engine that needs to be defined

    • nlp_engine_name
    • models
  • SPACY_ENTITIES : List of entities, that need to be handled by Spacy

  • TRANSFORMER_MODELS_ENTITIES : List of entities, that need to be handled by the Transformers models

  • TRANSFORMER_MODELS_ENHANCERS : Post processing enhancement for the Tags provided by the Transformers models (Extending partial words or merging similar contiguous entities)

in anonymizer_config_default.yaml the following can be defined :

  • AVAILABLE_LANGS : Which language Canonym can handle, defaults to en and fr

  • DEFAULT_ENTITIES: List of all entities that can be anonymized

  • ALPHABET_ENTITIES: Set of Alphabet entities

  • SPECIAL_ENTITIES: Set of special entities ( email, url, etc..)

  • NUMERIC_ENTITIES:

  • ALPHANUMERIC_ENTITIES:

  • CUSTOM_ENTITIES: Custom set of entities to be redacted

  • ALL_ANONYMIZER_STRATEGIES: List of strategies, a strategy is defined as :
    strategy_name : {anonymization_action_1 : SET_1_OF_ENTITES, anonymization_action_2 : SET_2_OF_ENTITES}

Contributing

Before contributing please read the instructions in CONTRIBUTING.md

link: CONTRIBUTING.MD

License

MIT License

Canonym - Librairie d'anonymisation Statistique Canada

Installation

Créer un environnement virtuel avec Python >=3.9 ... code:

conda create -n=canonym python=3.9
conda activate canonym

Vous pouvez installer Canonym en utilisant le fichier whl situé dans le dossier dist :

... code:

pip install dist\canonym_public-2023.9.15-py3-none-any.whl

Utilisation

Utilisation de base

... code:: python

from canonym import Canonym

anonymizer = Canonym()

text = "This is John Doe, from Ottawa, his phone number is 123-456-7890" anonymizer.anonymize(text)

Canonym peut accepter comme intrants :

  • chaîne de caractères
  • liste de chaînes de caractères
  • objet Textitem
  • Série Pandas
  • DataFrame Pandas

Vous pouvez utiliser directement la méthode anonymize(), ou utiliser les méthodes spécifiques à chaque type d'intrants :

  • str : anonymizer.anonymize_text,
  • TextItem : anonymizer.anonymize_text,
  • list : anonymizer.anonymize_list,
  • DataFrame : anonymizer.anonymize_dataframe,
  • Series : anonymizer.anonymize_pd_series

Stratégies

Les stratégies suivantes sont disponibles par défaut :

  • replace_all_with_tag : remplace toutes les entités par leur type d'entité.
  • redact_all : expurge tous les PI
  • hash_all : Hache les entités PI
  • mask_all : Masque toutes les entités DEFAULT
  • scramble_all : Brouille (change l'ordre des lettres) toutes les entités.
  • mixed_per_entity_type : {hash : ALPHABET_ENTITIES, mask : SPECIAL_ENTITIES, randomize : NUMERIC_ENTITIES, redact : ALPHANUMERIC_ENTITIES}
  • hash_one : {hash : [PERSON]}
  • mask_some : {mask : [PERSON, FULL_ADDRESS], redact : [PHONE_NUMBER]}
  • replace_custom : {replace : CUSTOM_ENTITIES}
  • redact_custom : {redact : CUSTOM_ENTITIES}
  • faker_custom : {faker : CUSTOM_ENTITIES}
  • faker_all : {faker : DEFAULT_ENTITIES}
  • replace_w_value_custom : {replace_val : CUSTOM_ENTITIES}

Par défaut, la méthode d'anonymisation utilise la stratégie replace_all_with_tag, pour utiliser une stratégie différente, utilisez :

   anonymizer.anonymize(text, strategy='redact_all')

Langue

Le paramètre language indique la langue du texte, par défaut l'anglais, si None ou "auto" sont fournis, une recherche sera effectuée pour trouver automatiquement la bonne langue pour chaque entrée de texte pour trouver automatiquement la bonne langue pour chaque texte saisi. Par défaut, Canonym est capable de traiter les textes en anglais et en français.

Dans le cas d'un DataFrame Pandas, Canonym accepte également un dict de format {nom_de_colonne:langue ou auto, }, afin que chaque colonne puisse être configurée pour une langue différente ou pour une recherche automatique.

# une chaîne de caractères
anonymizer.anonymize(text, strategy='redact_all', language='fr')
# un DataFrame Pandas
anonymizer.anonymize(df, language={'column1' : 'en', 'column2' : 'fr', 'column3' : 'auto'} )

Configuration avancée

Le comportement de Canonym peut être modifié en éditant les deux fichiers de configuration :

  • ner_config_default.yaml
  • anonymizer_config_default.yaml

dans ner_config_default.yaml les éléments suivants peuvent être définis :

  • AVAILABLE_LANGS : Les langues que Canonym peut gérer, par défaut en et fr.

  • SCORE_THRESHOLD : Le seuil de confiance à partir duquel une entité est étiquetée, par défaut 0.4.

  • DEFAULT_RECOGNIZERS : Liste des outils de reconnaissance chargés par Canonym

  • POST_PROCESSING_ENTITIES : Post-traitement spécifique aux entités

  • PRESIDIO_NLP_ENGINE_CONFIG : Certaines entités seront traitées par un moteur spacy qui doit être défini.

    • nom du moteur nlp
    • modèles
  • SPACY_ENTITIES : Liste des entités qui doivent être gérées par Spacy

  • TRANSFORMER_MODELS_ENTITIES : Liste des entités qui doivent être traitées par les modèles Transformers

  • TRANSFORMER_MODELS_ENHANCERS : Amélioration du post-traitement pour les étiquettes fournies par les modèles Transformers (extension des mots partiels ou fusion d'entités contiguës similaires)

dans anonymizer_config_default.yaml, les éléments suivants peuvent être définis :

  • AVAILABLE_LANGS : Les langues que Canonym peut gérer, par défaut en et fr.

  • DEFAULT_ENTITIES : Liste de toutes les entités qui peuvent être anonymisées

  • ALPHABET_ENTITIES : Ensemble d'entités alphabétiques

  • SPECIAL_ENTITIES : Ensemble d'entités spéciales (email, url, etc.)

  • NUMERIC_ENTITIES :

  • ALPHANUMERIC_ENTITIES :

  • CUSTOM_ENTITIES : Ensemble personnalisé d'entités à expurger

  • ALL_ANONYMIZER_STRATEGIES : Liste des stratégies, une stratégie est définie comme suit :
    nom_de_la_stratégie : {anonymisation_action_1 : SET_1_OF_ENTITES, anonymisation_action_2 : SET_2_OF_ENTITES}

Contribuer

Avant de contribuer merci de lire les instructions présentes dans CONTRIBUTING.md

lien: CONTRIBUTING.MD

License

MIT License

canonym's People

Contributors

alexandre-ist avatar alexandre-istrate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

canonym's Issues

Issue when punctuation found at the end of a chunk

Hi, I've been testing out the Canonym package with our data, and I ran into an error: IndexError: list index out of range

It occurred when processing a long text string, which causes the transformer recognizer to split the text into chunks. The chunking code, as far as I can tell, tries to split text at the end of a sentence when possible. By chance, one of the chunks ended with punctuation already -- the last token was a "." character. The code then causes an issue at this line: https://github.com/StatCan/Canonym/blob/main/src/canonym/recognizers/transformer_recognizers.py#L153

Basically, the use of a negative index will typically count items starting from the end of the list, but in this case it ended up trying to split at tokens[:-0], tokens[-0:], which does the opposite of what it should (it puts all the tokens in the "overflow", rather than including all the tokens in the chunk). It's one of the drawbacks of using this sort of negative index.

The code ultimately hits an error here when it tries to index into an empty list: https://github.com/StatCan/Canonym/blob/main/src/canonym/recognizers/transformer_recognizers.py#L134

As far as I can tell, the i == 0 is really just a special case, as the negative index should work for all other values, so I think you just need a special if statement to capture it:

if i == 0:
    return tokens, []
else:
    return tokens[:-i], tokens[-i:]

I'm happy to submit a pull request to make this change, if that's easier.

Otherwise, I haven't run into any issues testing the package yet -- thanks for putting together such a useful package!

Jeff Hughes, ESDC

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.