alisrbdni langdonholmes commited on
Commit
7dda936
0 Parent(s):

Duplicate from langdonholmes/piilo

Browse files

Co-authored-by: Langdon Holmes <[email protected]>

Files changed (12) hide show
  1. .gitattributes +34 -0
  2. .gitignore +1 -0
  3. LICENSE +202 -0
  4. Pipfile +22 -0
  5. Pipfile.lock +0 -0
  6. README.md +26 -0
  7. analyzer.py +141 -0
  8. anonymizer.py +140 -0
  9. app.py +160 -0
  10. data/ascii_names.parquet +3 -0
  11. names_database.py +35 -0
  12. requirements.txt +0 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ __pycache__/*
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
Pipfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [[source]]
2
+ url = "https://pypi.org/simple"
3
+ verify_ssl = true
4
+ name = "pypi"
5
+
6
+ [packages]
7
+ pandas = "==1.4.3"
8
+ presidio-analyzer = "==2.2.28"
9
+ presidio-anonymizer = "==2.2.28"
10
+ spacy = "==3.4.1"
11
+ spacy-transformers = "==1.1.7"
12
+ st-annotated-text = "==3.0.0"
13
+ streamlit = "==1.17.0"
14
+ tokenizers = "==0.12.1"
15
+ torch = "==1.12.0"
16
+ en-student-name-detector = {file = "https://huggingface.co/langdonholmes/en_student_name_detector/resolve/main/en_student_name_detector-any-py3-none-any.whl"}
17
+ names-dataset = "*"
18
+
19
+ [dev-packages]
20
+
21
+ [requires]
22
+ python_version = "3.10"
Pipfile.lock ADDED
The diff for this file is too large to render. See raw diff
 
README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Piilo
3
+ emoji: 🏃
4
+ colorFrom: purple
5
+ colorTo: purple
6
+ sdk: streamlit
7
+ sdk_version: 1.10.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ duplicated_from: langdonholmes/piilo
12
+ ---
13
+
14
+ For development, try working with pipenv:
15
+
16
+ 1. Clone the repository
17
+ `git clone https://huggingface.co/spaces/langdonholmes/piilo`
18
+
19
+ 2. Install dependencies from Pipfile
20
+ `pip install --user pipenv`
21
+
22
+ 3. Run streamlit app
23
+ `streamlit run .\app.py`
24
+
25
+ TODO:
26
+ Create a command line version using Typer in this same repository.
analyzer.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional, List, Tuple, Set
3
+
4
+ from presidio_analyzer import (AnalysisExplanation, AnalyzerEngine,
5
+ LocalRecognizer, RecognizerRegistry,
6
+ RecognizerResult)
7
+ from presidio_analyzer.nlp_engine import NlpArtifacts, NlpEngineProvider
8
+
9
+ logger = logging.getLogger('presidio-analyzer')
10
+
11
+ class CustomSpacyRecognizer(LocalRecognizer):
12
+ ENTITIES = [
13
+ 'STUDENT',
14
+ ]
15
+
16
+ DEFAULT_EXPLANATION = 'Identified as {} by a Student Name Detection Model'
17
+
18
+ CHECK_LABEL_GROUPS = [
19
+ ({'STUDENT'}, {'STUDENT'}),
20
+ ]
21
+
22
+ MODEL_LANGUAGES = {
23
+ 'en': 'langdonholmes/en_student_name_detector',
24
+ }
25
+
26
+ def __init__(
27
+ self,
28
+ supported_language: str = 'en',
29
+ supported_entities: Optional[List[str]] = None,
30
+ check_label_groups: Optional[Tuple[Set, Set]] = None,
31
+ ner_strength: float = 0.85,
32
+ ):
33
+ self.ner_strength = ner_strength
34
+ self.check_label_groups = (
35
+ check_label_groups if check_label_groups else self.CHECK_LABEL_GROUPS
36
+ )
37
+ supported_entities = supported_entities if supported_entities else self.ENTITIES
38
+ super().__init__(
39
+ supported_entities=supported_entities,
40
+ supported_language=supported_language,
41
+ )
42
+
43
+ def load(self) -> None:
44
+ '''Load the model, not used. Model is loaded during initialization.'''
45
+ pass
46
+
47
+ def get_supported_entities(self) -> List[str]:
48
+ '''
49
+ Return supported entities by this model.
50
+ :return: List of the supported entities.
51
+ '''
52
+ return self.supported_entities
53
+
54
+ def build_spacy_explanation(
55
+ self, original_score: float, explanation: str
56
+ ) -> AnalysisExplanation:
57
+ '''
58
+ Create explanation for why this result was detected.
59
+ :param original_score: Score given by this recognizer
60
+ :param explanation: Explanation string
61
+ :return:
62
+ '''
63
+ explanation = AnalysisExplanation(
64
+ recognizer=self.__class__.__name__,
65
+ original_score=original_score,
66
+ textual_explanation=explanation,
67
+ )
68
+ return explanation
69
+
70
+ def analyze(self,
71
+ text: str,
72
+ entities: List[str] = None,
73
+ nlp_artifacts: NlpArtifacts = None):
74
+ '''Analyze input using Analyzer engine and input arguments (kwargs).'''
75
+
76
+ if not entities or 'All' in entities:
77
+ entities = None
78
+
79
+ results = []
80
+
81
+ if not nlp_artifacts:
82
+ logger.warning('Skipping SpaCy, nlp artifacts not provided...')
83
+ return results
84
+
85
+ ner_entities = nlp_artifacts.entities
86
+
87
+ for entity in entities:
88
+ if entity not in self.supported_entities:
89
+ continue
90
+ for ent in ner_entities:
91
+ if not self.__check_label(entity, ent.label_, self.check_label_groups):
92
+ continue
93
+ textual_explanation = self.DEFAULT_EXPLANATION.format(
94
+ ent.label_)
95
+ explanation = self.build_spacy_explanation(
96
+ self.ner_strength, textual_explanation
97
+ )
98
+ spacy_result = RecognizerResult(
99
+ entity_type=entity,
100
+ start=ent.start_char,
101
+ end=ent.end_char,
102
+ score=self.ner_strength,
103
+ analysis_explanation=explanation,
104
+ recognition_metadata={
105
+ RecognizerResult.RECOGNIZER_NAME_KEY: self.name
106
+ },
107
+ )
108
+ results.append(spacy_result)
109
+
110
+ return results
111
+
112
+ @staticmethod
113
+ def __check_label(
114
+ entity: str, label: str, check_label_groups: Tuple[Set, Set]
115
+ ) -> bool:
116
+ return any(
117
+ [entity in egrp and label in lgrp for egrp, lgrp in check_label_groups]
118
+ )
119
+
120
+ def prepare_analyzer(configuration):
121
+ '''Handle Preparation of Analyzer Engine for Presidio.'''
122
+
123
+ spacy_recognizer = CustomSpacyRecognizer()
124
+
125
+ # Create NLP engine based on configuration
126
+ provider = NlpEngineProvider(nlp_configuration=configuration)
127
+ nlp_engine = provider.create_engine()
128
+
129
+ # add rule-based recognizers
130
+ registry = RecognizerRegistry()
131
+ registry.load_predefined_recognizers(nlp_engine=nlp_engine)
132
+ registry.add_recognizer(spacy_recognizer)
133
+
134
+ # remove the nlp engine we passed, to use custom label mappings
135
+ registry.remove_recognizer('SpacyRecognizer')
136
+
137
+ analyzer = AnalyzerEngine(nlp_engine=nlp_engine,
138
+ registry=registry,
139
+ supported_languages=['en'])
140
+
141
+ return analyzer
anonymizer.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import List, Optional, Tuple
4
+
5
+ import pandas as pd
6
+ from presidio_analyzer import RecognizerResult
7
+ from presidio_anonymizer import AnonymizerEngine
8
+ from presidio_anonymizer.entities import OperatorConfig
9
+ from presidio_anonymizer.operators import OperatorType
10
+
11
+ from names_database import NameDatabase
12
+
13
+ name_table = Path('data', 'ascii_names.parquet')
14
+
15
+ logger = logging.getLogger('anonymizer')
16
+
17
+ class surrogate_anonymizer(AnonymizerEngine):
18
+ def __init__(self):
19
+ super().__init__()
20
+ self.names_db = NameDatabase()
21
+ self.names_df = pd.read_parquet(name_table)
22
+
23
+ def get_random_name(
24
+ self,
25
+ country: Optional[str] = None,
26
+ gender: Optional[str] = None
27
+ ) -> pd.DataFrame:
28
+ '''Returns two random names from the database as a DataFrame.
29
+ Both rows match gender and country, if provided.
30
+ :country: ISO country code e.g. "CO" for Columbia
31
+ :gender: 'M' or 'F'
32
+ returns two rows of the names dataframe
33
+ '''
34
+ names_view = self.names_df
35
+ if country:
36
+ names_view = names_view[names_view['country'] == country]
37
+ if gender:
38
+ names_view = names_view[names_view['gender'] == gender]
39
+ if names_view.size < 25:
40
+ return self.names_df.sample(n=2, weights=self.names_df['count'])
41
+ return names_view.sample(n=2, weights=names_view['count'])
42
+
43
+ def split_name(self, original_name: str) -> Tuple[str]:
44
+ '''Splits name into parts.
45
+ If one token, assume it is a first name.
46
+ If two tokens, first and last name.
47
+ If three tokens, one first name and two last names.
48
+ If four tokens, two first names and two last names.'''
49
+ names = original_name.split()
50
+ if len(names) == 1:
51
+ logger.info(f'Splitting to 1 first name: {names}')
52
+ return names[0], None
53
+ elif len(names) == 2:
54
+ logger.info(f'Splitting to 1 first name, 1 last name: {names}')
55
+ return names[0], names[1]
56
+ elif len(names) == 3:
57
+ logger.info(f'Splitting to 1 first name, 2 last names: {names}')
58
+ return names[0], ' '.join(names[1:])
59
+ elif len(names) == 4:
60
+ logger.info(f'Splitting to 2 first names and 2 last names: {names}')
61
+ return ' '.join(names[:2]), ' '.join(names[2:])
62
+ else:
63
+ logger.info(f'Splitting failed, do not match gender/country: {names}')
64
+ return None, None
65
+
66
+ def generate_surrogate(self, original_name: str) -> str:
67
+ '''Generate a surrogate name.
68
+ '''
69
+ if original_name == 'PII':
70
+ # Every time we call this function, Presidio will validate it
71
+ # by testing that the function returns a str when the input is
72
+ # 'PII'. Bypass this test.
73
+ return 'PII'
74
+
75
+ first_names, last_names = self.split_name(original_name)
76
+ gender = self.names_db.get_gender(first_names) if first_names else None
77
+ logger.debug(f'Gender set to {gender}')
78
+ country = self.names_db.get_country(last_names) if last_names else None
79
+ logger.debug(f'Country set to {country}')
80
+
81
+ surrogate_name = ''
82
+
83
+ name_candidates = self.get_random_name(gender=gender, country=country)
84
+
85
+ surrogate_name += name_candidates.iloc[0]['first']
86
+ logger.info(f'First name surrogate is {surrogate_name}')
87
+
88
+ if last_names:
89
+ logger.info(f'Combining with {name_candidates.iloc[1]["last"]}')
90
+ surrogate_name += ' ' + name_candidates.iloc[1]['last']
91
+
92
+ logger.info(f'Returning surrogate name {surrogate_name}')
93
+ return surrogate_name
94
+
95
+ def anonymize(
96
+ self,
97
+ text: str,
98
+ analyzer_results: List[RecognizerResult]
99
+ ):
100
+ '''Anonymize identified input using Presidio Anonymizer.'''
101
+
102
+ if not text:
103
+ return
104
+
105
+ analyzer_results = self._remove_conflicts_and_get_text_manipulation_data(
106
+ analyzer_results
107
+ )
108
+
109
+ operators = self._AnonymizerEngine__check_or_add_default_operator(
110
+ {
111
+ 'STUDENT': OperatorConfig('custom',
112
+ {'lambda': self.generate_surrogate}),
113
+ 'EMAIL_ADDRESS': OperatorConfig('replace',
114
+ {'new_value': '[email protected]'}),
115
+ 'PHONE_NUMBER': OperatorConfig('replace',
116
+ {'new_value': '888-888-8888'}),
117
+ 'URL': OperatorConfig('replace',
118
+ {'new_value': 'aol.com'}),
119
+ }
120
+ )
121
+
122
+ res = self._operate(text,
123
+ analyzer_results,
124
+ operators,
125
+ OperatorType.Anonymize)
126
+
127
+ return res.text
128
+
129
+ if __name__ == '__main__':
130
+ logging.basicConfig(level=logging.DEBUG)
131
+ anonymizer = surrogate_anonymizer()
132
+ test_names = ['Nora Wang',
133
+ 'MJ',
134
+ '',
135
+ '(',
136
+ 'Mario Escobar Sanchez',
137
+ 'Jane Fonda Michelle Rousseau',
138
+ 'Sir Phillipe Ricardo de la Sota Mayor']
139
+ for name in test_names:
140
+ anonymizer.generate_surrogate(name)
app.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ '''Streamlit app for Student Name Detection models.'''
3
+
4
+ from analyzer import prepare_analyzer
5
+ from anonymizer import surrogate_anonymizer
6
+ from presidio_anonymizer import AnonymizerEngine
7
+ import pandas as pd
8
+ from annotated_text import annotated_text
9
+ from json import JSONEncoder
10
+ import json
11
+ import warnings
12
+ import streamlit as st
13
+ import os
14
+ os.environ['TOKENIZERS_PARALLELISM'] = 'false'
15
+ warnings.filterwarnings('ignore')
16
+
17
+ # Helper methods
18
+ @st.cache(allow_output_mutation=True)
19
+ def analyzer_engine():
20
+ '''Return AnalyzerEngine and cache with Streamlit.'''
21
+
22
+ configuration = {
23
+ 'nlp_engine_name': 'spacy',
24
+ 'models': [
25
+ {'lang_code': 'en', 'model_name': 'en_student_name_detector'}],
26
+ }
27
+
28
+ analyzer = prepare_analyzer(configuration)
29
+
30
+ return analyzer
31
+
32
+ @st.cache(allow_output_mutation=True)
33
+ def anonymizer_engine():
34
+ '''Return generate surrogate anonymizer.'''
35
+ return surrogate_anonymizer()
36
+
37
+ def annotate(text, st_analyze_results, st_entities):
38
+ tokens = []
39
+ # sort by start index
40
+ results = sorted(st_analyze_results, key=lambda x: x.start)
41
+ for i, res in enumerate(results):
42
+ if i == 0:
43
+ tokens.append(text[:res.start])
44
+
45
+ # append entity text and entity type
46
+ tokens.append((text[res.start: res.end], res.entity_type))
47
+
48
+ # if another entity coming i.e. we're not at the last results element, add text up to next entity
49
+ if i != len(results) - 1:
50
+ tokens.append(text[res.end:results[i+1].start])
51
+ # if no more entities coming, add all remaining text
52
+ else:
53
+ tokens.append(text[res.end:])
54
+ return tokens
55
+
56
+
57
+ st.set_page_config(page_title='Student Name Detector (English)', layout='wide')
58
+
59
+ # Side bar
60
+ st.sidebar.markdown(
61
+ '''Detect and anonymize PII in text using an [NLP model](https://huggingface.co/langdonholmes/en_student_name_detector) [trained](https://github.com/aialoe/deidentification-pipeline) on student-generated text collected by Coursera.
62
+ '''
63
+ )
64
+
65
+ st_entities = st.sidebar.multiselect(
66
+ label='Which entities to look for?',
67
+ options=analyzer_engine().get_supported_entities(),
68
+ default=list(analyzer_engine().get_supported_entities()),
69
+ )
70
+
71
+ st_threshold = st.sidebar.slider(
72
+ label='Acceptance threshold', min_value=0.0, max_value=1.0, value=0.35
73
+ )
74
+
75
+ st_return_decision_process = st.sidebar.checkbox(
76
+ 'Add analysis explanations in json')
77
+
78
+ st.sidebar.info(
79
+ 'This is part of a deidentification project for student-generated text.'
80
+ )
81
+
82
+ # Main panel
83
+ analyzer_load_state = st.info(
84
+ 'Starting Presidio analyzer and loading Longformer-based model...')
85
+ engine = analyzer_engine()
86
+ analyzer_load_state.empty()
87
+
88
+
89
+ st_text = st.text_area(
90
+ label='Type in some text',
91
+ value='Learning Reflection\n\nWritten by John Williams and Samantha Morales\n\nIn this course I learned many things. As Liedtke (2004) said, \"Students grow when they learn\" (Erickson et al. 1998).\n\nBy John H. Williams -- (714) 328-9989 -- [email protected]',
92
+ height=200,
93
+ )
94
+
95
+ button = st.button('Detect PII')
96
+
97
+ if 'first_load' not in st.session_state:
98
+ st.session_state['first_load'] = True
99
+
100
+ # After
101
+ st.subheader('Analyzed')
102
+ with st.spinner('Analyzing...'):
103
+ if button or st.session_state.first_load:
104
+ st_analyze_results = analyzer_engine().analyze(
105
+ text=st_text,
106
+ entities=st_entities,
107
+ language='en',
108
+ score_threshold=st_threshold,
109
+ return_decision_process=st_return_decision_process,
110
+ )
111
+ annotated_tokens = annotate(st_text, st_analyze_results, st_entities)
112
+ # annotated_tokens
113
+ annotated_text(*annotated_tokens)
114
+
115
+ # vertical space
116
+ st.text('')
117
+
118
+ st.subheader('Anonymized')
119
+ with st.spinner('Anonymizing...'):
120
+ if button or st.session_state.first_load:
121
+ st_anonymize_results = anonymizer_engine().anonymize(
122
+ st_text,
123
+ st_analyze_results)
124
+ st_anonymize_results
125
+
126
+ # table result
127
+ st.subheader('Detailed Findings')
128
+ if st_analyze_results:
129
+ res_dicts = [r.to_dict() for r in st_analyze_results]
130
+ for d in res_dicts:
131
+ d['Value'] = st_text[d['start']:d['end']]
132
+ df = pd.DataFrame.from_records(res_dicts)
133
+ df = df[['entity_type', 'Value', 'score', 'start', 'end']].rename(
134
+ {
135
+ 'entity_type': 'Entity type',
136
+ 'start': 'Start',
137
+ 'end': 'End',
138
+ 'score': 'Confidence',
139
+ },
140
+ axis=1,
141
+ )
142
+
143
+ st.dataframe(df, width=1000)
144
+ else:
145
+ st.text('No findings')
146
+
147
+ st.session_state['first_load'] = True
148
+
149
+ # json result
150
+ class ToDictListEncoder(JSONEncoder):
151
+ '''Encode dict to json.'''
152
+
153
+ def default(self, o):
154
+ '''Encode to JSON using to_dict.'''
155
+ if o:
156
+ return o.to_dict()
157
+ return []
158
+
159
+ if st_return_decision_process:
160
+ st.json(json.dumps(st_analyze_results, cls=ToDictListEncoder))
data/ascii_names.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:baf5cf2fa43dc172c613f72793641f668e33c30b4e23932616de36cc0ce3447d
3
+ size 33601747
names_database.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+
4
+ from names_dataset import NameDataset, NameWrapper
5
+
6
+
7
+ class NameDatabase(NameDataset):
8
+ def __init__(self) -> None:
9
+ super().__init__()
10
+
11
+ self.logger = logging.getLogger('anonymizer')
12
+
13
+ def search(self, name: str) -> dict:
14
+ '''Returns all entries associated with a name string.
15
+ The name string can be multiple tokens.
16
+ Both first and last names will be matched.
17
+ '''
18
+ key = name.strip().title()
19
+ fn = self.first_names.get(key) if self.first_names is not None else None
20
+ ln = self.last_names.get(key) if self.last_names is not None else None
21
+ return {'first_name': fn, 'last_name': ln}
22
+
23
+ def get_gender(self, first_names: str) -> str:
24
+ '''Return the most frequent gender code for a specific last name,
25
+ or None if a match cannot be found.
26
+ '''
27
+ gender = NameWrapper(self.search(first_names)).gender
28
+ return gender if gender else None
29
+
30
+ def get_country(self, last_names: str) -> str:
31
+ '''Return the most frequent country code for a specific last name,
32
+ or None if a match cannot be found.
33
+ '''
34
+ country = NameWrapper(self.search(last_names)).country
35
+ return country if country else None
requirements.txt ADDED
Binary file (8.63 kB). View file