forked from microsoft/presidio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecognizerRegistry.cs
More file actions
299 lines (258 loc) · 10.7 KB
/
RecognizerRegistry.cs
File metadata and controls
299 lines (258 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System.Collections.Concurrent;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ManagedCode.Presidio.Analyzer;
/// <summary>
/// Holds the collection of recognizers available to the analyzer engine.
/// </summary>
public sealed class RecognizerRegistry
{
private readonly List<EntityRecognizer> _recognizers;
private readonly HashSet<string> _supportedLanguages;
private static readonly ConcurrentDictionary<string, Type?> RecognizerTypeCache = new(StringComparer.Ordinal);
private RegexOptions _globalRegexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline;
public RecognizerRegistry(
IEnumerable<EntityRecognizer>? recognizers = null,
IEnumerable<string>? supportedLanguages = null)
{
_recognizers = recognizers?.ToList() ?? new List<EntityRecognizer>();
_supportedLanguages = supportedLanguages is null
? new HashSet<string>(_recognizers.Select(r => r.SupportedLanguage), StringComparer.OrdinalIgnoreCase)
: new HashSet<string>(supportedLanguages, StringComparer.OrdinalIgnoreCase);
}
public IReadOnlyCollection<EntityRecognizer> RegisteredRecognizers => _recognizers;
public IReadOnlyCollection<string> SupportedLanguages => _supportedLanguages;
public void AddRecognizer(EntityRecognizer recognizer)
{
ArgumentNullException.ThrowIfNull(recognizer);
ApplyGlobalRegexOptions(recognizer);
_recognizers.Add(recognizer);
_supportedLanguages.Add(recognizer.SupportedLanguage);
}
public void RemoveRecognizer(string recognizerName, string? language = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(recognizerName);
_recognizers.RemoveAll(recognizer =>
string.Equals(recognizer.Name, recognizerName, StringComparison.Ordinal)
&& (language is null || string.Equals(recognizer.SupportedLanguage, language, StringComparison.Ordinal)));
}
public IReadOnlyCollection<EntityRecognizer> GetRecognizers(
string language,
IReadOnlyCollection<string>? entities = null,
bool allFields = false,
IReadOnlyCollection<EntityRecognizer>? adHocRecognizers = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(language);
if (!allFields && (entities is null || entities.Count == 0))
{
throw new ArgumentException("No entities provided.", nameof(entities));
}
var candidates = new List<EntityRecognizer>(_recognizers);
if (adHocRecognizers is not null)
{
candidates.AddRange(adHocRecognizers);
}
var filtered = allFields
? candidates
: candidates.Where(recognizer =>
string.Equals(recognizer.SupportedLanguage, language, StringComparison.Ordinal)
&& recognizer.SupportedEntities.Intersect(entities ?? Array.Empty<string>(), StringComparer.Ordinal).Any());
var result = filtered
.Distinct()
.ToList();
if (result.Count == 0)
{
throw new InvalidOperationException("No matching recognizers were found to serve the request.");
}
return result;
}
public IReadOnlyCollection<string> GetSupportedEntities(IReadOnlyCollection<string>? languages = null)
{
var targetLanguages = (languages is null || languages.Count == 0) ? _supportedLanguages : languages;
return _recognizers
.Where(recognizer => targetLanguages.Contains(recognizer.SupportedLanguage))
.SelectMany(recognizer => recognizer.SupportedEntities)
.Distinct(StringComparer.Ordinal)
.ToArray();
}
public void LoadPredefinedRecognizers(
RecognizerRegistryConfiguration configuration,
INlpEngine? nlpEngine = null,
IReadOnlyCollection<string>? languages = null)
{
ArgumentNullException.ThrowIfNull(configuration);
_globalRegexOptions = configuration.GlobalRegexOptions;
if (configuration.SupportedLanguages.Count > 0)
{
_supportedLanguages.UnionWith(configuration.SupportedLanguages);
}
foreach (var definition in configuration.Recognizers)
{
if (!definition.Enabled)
{
continue;
}
if (!string.Equals(definition.Type, "predefined", StringComparison.OrdinalIgnoreCase))
{
// TODO: support custom recognizer definitions (type: custom)
continue;
}
var recognizerType = ResolveRecognizerType(definition.Name);
if (recognizerType is null)
{
// TODO: add logging once tracing infrastructure is in place.
continue;
}
foreach (var languageConfiguration in definition.Languages)
{
if (HasRecognizer(recognizerType, languageConfiguration.Language))
{
continue;
}
var recognizer = InstantiatePredefinedRecognizer(recognizerType, languageConfiguration);
if (recognizer is null)
{
continue;
}
AddRecognizer(recognizer);
}
}
if (nlpEngine is not null)
{
AddNlpRecognizer(nlpEngine);
}
}
public void AddNlpRecognizer(INlpEngine nlpEngine)
{
ArgumentNullException.ThrowIfNull(nlpEngine);
var supportedEntities = nlpEngine.GetSupportedEntities();
foreach (var language in nlpEngine.GetSupportedLanguages())
{
_supportedLanguages.Add(language);
if (_recognizers.Any(r => r is OnnxNerRecognizer existing && string.Equals(existing.SupportedLanguage, language, StringComparison.OrdinalIgnoreCase)))
{
continue;
}
var recognizer = new OnnxNerRecognizer(language, supportedEntities);
_recognizers.Add(recognizer);
}
}
private static Type? ResolveRecognizerType(string recognizerName)
{
if (RecognizerTypeCache.TryGetValue(recognizerName, out var cached))
{
return cached;
}
var assembly = typeof(RecognizerRegistry).Assembly;
var type = assembly
.GetTypes()
.FirstOrDefault(candidate =>
typeof(EntityRecognizer).IsAssignableFrom(candidate) &&
string.Equals(candidate.Name, recognizerName, StringComparison.Ordinal));
RecognizerTypeCache[recognizerName] = type;
return type;
}
private bool HasRecognizer(Type recognizerType, string language) =>
_recognizers.Any(existing =>
existing.GetType() == recognizerType &&
string.Equals(existing.SupportedLanguage, language, StringComparison.OrdinalIgnoreCase));
private EntityRecognizer? InstantiatePredefinedRecognizer(
Type recognizerType,
RecognizerLanguageConfiguration languageConfiguration)
{
var constructors = recognizerType
.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
.OrderByDescending(ctor => ctor.GetParameters().Length);
foreach (var constructor in constructors)
{
try
{
var arguments = BuildConstructorArguments(constructor.GetParameters(), languageConfiguration);
if (constructor.Invoke(arguments) is EntityRecognizer recognizer)
{
ApplyGlobalRegexOptions(recognizer);
return recognizer;
}
}
catch (TargetInvocationException)
{
// Skip constructors that throw due to unsupported arguments and try the next overload.
}
catch (ArgumentException)
{
// Skip constructors that cannot be invoked with the generated arguments.
}
}
return null;
}
private object?[] BuildConstructorArguments(
IReadOnlyList<ParameterInfo> parameters,
RecognizerLanguageConfiguration languageConfiguration)
{
var arguments = new object?[parameters.Count];
var context = languageConfiguration.Context.Count > 0
? languageConfiguration.Context.ToArray()
: Array.Empty<string>();
for (var index = 0; index < parameters.Count; index++)
{
var parameter = parameters[index];
var parameterType = parameter.ParameterType;
if (IsPatternEnumerable(parameterType))
{
arguments[index] = null;
}
else if (typeof(IEnumerable<string>).IsAssignableFrom(parameterType))
{
arguments[index] = context.Length > 0 ? context : null;
}
else if (parameterType == typeof(string))
{
if (string.Equals(parameter.Name, "supportedLanguage", StringComparison.OrdinalIgnoreCase) ||
string.Equals(parameter.Name, "supported_language", StringComparison.OrdinalIgnoreCase) ||
string.Equals(parameter.Name, "language", StringComparison.OrdinalIgnoreCase))
{
arguments[index] = languageConfiguration.Language;
}
else if (parameter.HasDefaultValue)
{
arguments[index] = parameter.DefaultValue;
}
else
{
arguments[index] = string.Empty;
}
}
else if (parameterType == typeof(RegexOptions) || parameterType == typeof(RegexOptions?))
{
arguments[index] = _globalRegexOptions;
}
else if (parameter.HasDefaultValue)
{
arguments[index] = parameter.DefaultValue;
}
else if (parameterType.IsValueType)
{
arguments[index] = Activator.CreateInstance(parameterType);
}
else
{
arguments[index] = null;
}
}
return arguments;
}
private static bool IsPatternEnumerable(Type parameterType)
{
return parameterType.IsGenericType &&
parameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>) &&
parameterType.GenericTypeArguments.Length == 1 &&
parameterType.GenericTypeArguments[0] == typeof(Pattern);
}
private void ApplyGlobalRegexOptions(EntityRecognizer recognizer)
{
if (recognizer is PatternRecognizer patternRecognizer)
{
patternRecognizer.SetGlobalRegexOptions(_globalRegexOptions);
}
}
}