-
Notifications
You must be signed in to change notification settings - Fork 75
/
FastTokenizer.cs
714 lines (632 loc) · 28.9 KB
/
FastTokenizer.cs
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
using UID;
using Mosaik.Core;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
using System.Buffers;
namespace Catalyst.Models
{
[FormerName("Mosaik.NLU.Models", "SimpleTokenizer")]
public class FastTokenizer : ITokenizer, IProcess, ICanOptimizeMemory
{
public static bool DisableEmailOrURLCapture { get; set; } = false;
public static TimeSpan Timeout { get; set; } = TimeSpan.FromHours(1);
public Language Language { get; set; }
public string Type => typeof(FastTokenizer).FullName;
public string Tag => "";
public int Version => 0;
private readonly Dictionary<int, TokenizationException> _baseSpecialCases;
private Dictionary<int, TokenizationException> _customSpecialCases;
private HashSet<int> _customSimpleSpecialCases;
private ReaderWriterLockSlim _lockSpecialCases = new();
public static Task<FastTokenizer> FromStoreAsync(Language language, int version, string tag)
{
return Task.FromResult(new FastTokenizer(language));
}
public static Task<bool> ExistsAsync(Language language, int version, string tag)
{
return Task.FromResult(true);
} // Needs to say it exists, otherwise when calling StoredObjectInfo.ExistsAsync(Language language, int version, string tag), it will fail to load this model
public FastTokenizer(Language language)
{
Language = language;
_baseSpecialCases = TokenizerExceptions.Get(Language);
}
public void Process(IDocument document, CancellationToken cancellationToken = default)
{
Parse(document, cancellationToken);
}
public void Parse(IDocument document, CancellationToken cancellationToken = default)
{
if (document.SpansCount == 0)
{
document.AddSpan(0, document.Length - 1);
}
foreach (Span s in document.Spans)
{
try
{
Parse(s, cancellationToken);
}
catch (InvalidOperationException ome)
{
document.Clear();
throw new TokenizationFailedException($"Error tokenizing document:\n'{document.Value}'", ome);
}
catch (TaskCanceledException tce)
{
document.Clear();
throw new TokenizationFailedException($"Timeout tokenizing document:\n'{document.Value}'", tce);
}
}
}
public IEnumerable<IToken> Parse(string text, CancellationToken cancellationToken = default)
{
var tmpDoc = new Document(text);
Parse(tmpDoc, cancellationToken);
return tmpDoc.Spans.First().Tokens;
}
public void ImportSpecialCases(IProcess process)
{
if (process is IHasSpecialCases cases)
{
_lockSpecialCases.EnterWriteLock();
try
{
_customSpecialCases ??= new();
foreach (var sc in cases.GetSpecialCases())
{
_customSpecialCases[sc.Key] = sc.Value;
}
}
finally
{
_lockSpecialCases.ExitWriteLock();
}
}
if (process is IHasSimpleSpecialCases simpleCases)
{
_lockSpecialCases.EnterWriteLock();
try
{
_customSimpleSpecialCases ??= new();
foreach (var sc in simpleCases.GetSimpleSpecialCases())
{
_customSimpleSpecialCases.Add(sc);
}
}
finally
{
_lockSpecialCases.ExitWriteLock();
}
}
}
public void AddSpecialCase(string word, TokenizationException exception)
{
_lockSpecialCases.EnterWriteLock();
try
{
_customSpecialCases ??= new();
_customSpecialCases[word.CaseSensitiveHash32()] = exception;
}
finally
{
_lockSpecialCases.ExitWriteLock();
}
}
public void Parse(Span span, CancellationToken cancellationToken = default)
{
var sw = ValueStopwatch.StartNew();
var timeout = Timeout;
_lockSpecialCases.EnterReadLock();
try
{
var customSpecialCases = _customSpecialCases;
var customSimpleSpecialCases = _customSimpleSpecialCases;
var baseSpecialCases = _baseSpecialCases;
//TODO: Finish conversion to tokenize also on BracketsCharacters
//var separators = CharacterClasses.WhitespacesAndBracketsCharacters;
var separators = CharacterClasses.WhitespaceCharacters;
var textSpan = span.ValueAsSpan;
bool hasEmoji = false;
for (int i = 0; i < textSpan.Length - 1; i++)
{
if (textSpan.Slice(i).IsEmoji(out _))
{
hasEmoji = true; break;
}
}
var rentedSplitPoints = ArrayPool<SplitPoint>.Shared.Rent(textSpan.Length / 4);
var splitPoints = rentedSplitPoints;
var splitPointsCount = 0;
var infixLocation = new List<(int index, int length)>();
int offset = 0, sufix_offset = 0;
int checkEvery = 0;
while (true)
{
if (splitPointsCount > textSpan.Length)
{
throw new InvalidOperationException(); //If we found more splitting points than actual characters on the span, we hit a bug in the tokenizer
}
if (checkEvery++ % 1024 == 0)
{
if (timeout.Ticks > 0 && sw.GetElapsedTime() > timeout)
{
throw new TaskCanceledException("Timeout while parsing document");
}
cancellationToken.ThrowIfCancellationRequested();
}
offset += sufix_offset;
sufix_offset = 0;
if (offset > textSpan.Length) { break; }
var splitPoint = textSpan.IndexOfAny(separators, offset);
ReadOnlySpan<char> candidate;
//TODO: Finish conversion to tokenize also on BracketsCharacters
//if (splitPoint >= 0)
//{
// var c = textSpan[splitPoint];
// switch (c)
// {
// case '(':
// case ')':
// case '[':
// case ']':
// case '{':
// case '}':
// {
// AddSplitPoint(ref splitPoints, ref splitPointsCount, offset, splitPoint, SplitPointReason.Parenthesis);
// offset++; continue;
// }
// }
//}
if (splitPoint == offset)
{
//Happens on sequential separators
offset++; continue;
}
if (splitPoint < 0)
{
candidate = textSpan.Slice(offset);
splitPoint = offset + candidate.Length;
if (candidate.Length == 0) { break; }
}
else
{
candidate = textSpan.Slice(offset, splitPoint - offset);
}
//Special case to split also at emojis
if (hasEmoji)
{
for (int i = 0; i < (candidate.Length - 1); i++)
{
if (candidate.Slice(i).IsEmoji(out var emojiLength))
{
if (i == 0)
{
splitPoint = offset + emojiLength - 1;
candidate = candidate.Slice(0, emojiLength);
}
else
{
splitPoint = offset + i - 1;
candidate = candidate.Slice(0, i);
}
break;
}
}
}
while (!candidate.IsEmpty)
{
int hash = candidate.CaseSensitiveHash32();
if ((customSpecialCases is object && customSpecialCases.ContainsKey(hash)) ||
(customSimpleSpecialCases is object && customSimpleSpecialCases.Contains(hash))
|| baseSpecialCases.ContainsKey(hash))
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset, splitPoint - 1, SplitPointReason.Exception);
candidate = new ReadOnlySpan<char>();
offset = splitPoint + 1;
continue;
}
else if (candidate.IsLikeURLorEmail())
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset, splitPoint - 1, SplitPointReason.EmailOrUrl);
candidate = new ReadOnlySpan<char>();
offset = splitPoint + 1;
continue;
}
else if (hasEmoji && candidate.IsEmoji(out var emojiLength))
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset, offset + emojiLength - 1, SplitPointReason.Emoji);
candidate = candidate.Slice(emojiLength);
offset += emojiLength;
continue;
}
else
{
if (candidate.Length == 1)
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset, offset, SplitPointReason.SingleChar);
candidate = new ReadOnlySpan<char>();
offset = splitPoint + 1;
continue;
}
if (!candidate.IsAllLetterOrDigit())
{
if (candidate.IsSentencePunctuation() || candidate.IsHyphen() || candidate.IsSymbol())
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset, splitPoint - 1, SplitPointReason.Punctuation);
candidate = new ReadOnlySpan<char>();
offset = splitPoint + 1;
continue;
}
int prefixLocation = FindPrefix(candidate);
if (prefixLocation >= 0)
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset + prefixLocation, offset + prefixLocation, SplitPointReason.Prefix);
candidate = candidate.Slice(prefixLocation + 1);
offset += prefixLocation + 1;
continue;
}
var (sufixIndex, sufixLength) = FindSufix(candidate);
if (sufixIndex > -1)
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset + sufixIndex, offset + sufixIndex + sufixLength - 1, SplitPointReason.Sufix);
candidate = candidate.Slice(0, sufixIndex);
splitPoint = offset + sufixIndex;
sufix_offset += sufixLength;
continue;
}
FindInfix(candidate, infixLocation);
if (infixLocation.Count > 0)
{
int in_offset = offset;
foreach (var (index, length) in infixLocation)
{
if ((offset + index - 1) >= in_offset)
{
AddSplitPoint(ref splitPoints, ref splitPointsCount, in_offset, offset + index - 1, SplitPointReason.Infix);
}
//Test if the remaining is not an exception first
if ((in_offset - offset + index) <= candidate.Length)
{
var rest = candidate.Slice(in_offset - offset + index);
int hashRest = rest.CaseSensitiveHash32();
if ((customSpecialCases is object && customSpecialCases.ContainsKey(hashRest)) ||
(customSimpleSpecialCases is object && customSimpleSpecialCases.Contains(hashRest)) ||
baseSpecialCases.ContainsKey(hashRest))
{
in_offset = offset + index;
break;
}
}
in_offset = offset + index + length;
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset + index, offset + index + length - 1, SplitPointReason.Infix);
}
candidate = candidate.Slice(in_offset - offset);
offset = in_offset;
continue;
}
}
}
AddSplitPoint(ref splitPoints, ref splitPointsCount, offset, splitPoint - 1, SplitPointReason.Normal);
candidate = new ReadOnlySpan<char>();
offset = splitPoint + 1;
}
}
int spanBegin = span.Begin;
int pB = int.MinValue, pE = int.MinValue;
span.ReserveTokens(splitPointsCount);
#if NET5_0_OR_GREATER
var sortedSplitPoints = splitPoints.AsSpan(0, splitPointsCount);
if(splitPointsCount > 0)
{
System.MemoryExtensions.Sort(sortedSplitPoints , _splitPointSorter);
}
#else
var sortedSplitPoints = new List<SplitPoint>(splitPointsCount);
foreach(var sp in splitPoints.AsSpan(0, splitPointsCount))
{
sortedSplitPoints.Add(sp);
}
sortedSplitPoints.Sort(_splitPointSorter);
#endif
foreach (var sp in sortedSplitPoints)
{
if (checkEvery++ % 1024 == 0)
{
if (timeout.Ticks > 0 && sw.GetElapsedTime() > timeout)
{
throw new TaskCanceledException("Timeout while parsing document");
}
cancellationToken.ThrowIfCancellationRequested();
}
int b = sp.Begin;
int e = sp.End;
if (pB == b && pE == e) { continue; }
pB = b; pE = e;
if (b > e)
{
#if DEBUG
throw new InvalidOperationException($"Error processing text: '{span.Value}', found token with begin={b} and end={e}");
#else
continue; //Ignore this token
#endif
}
while (char.IsWhiteSpace(textSpan[b]) && b < e) { b++; }
while (char.IsWhiteSpace(textSpan[e]) && e > b) { e--; }
int hash = textSpan.Slice(b, e - b + 1).CaseSensitiveHash32();
if (e < b)
{
continue;
}
if (customSimpleSpecialCases is object && customSimpleSpecialCases.Contains(hash))
{
var tk = span.AddToken(spanBegin + b, spanBegin + e);
}
else if ((customSpecialCases is object && customSpecialCases.TryGetValue(hash, out TokenizationException exp)) || baseSpecialCases.TryGetValue(hash, out exp))
{
if (exp.Replacements is null)
{
var tk = span.AddToken(spanBegin + b, spanBegin + e);
}
else
{
//TODO: Tokens begins and ends are being artificially placed here, check in the future how to better handle this
int begin2 = spanBegin + b;
for (int i = 0; i < exp.Replacements.Length; i++)
{
//Adds replacement tokens sequentially, consuming one char from the original document at a time, and
//using the remaing chars in the last replacement token
var tk = span.AddToken(begin2, ((i == exp.Replacements.Length - 1) ? (spanBegin + e) : begin2));
tk.Replacement = exp.Replacements[i];
begin2++;
}
}
}
else
{
var tk = span.AddToken(spanBegin + b, spanBegin + e);
if (sp.Reason == SplitPointReason.EmailOrUrl && !DisableEmailOrURLCapture)
{
tk.AddEntityType(new EntityType("EmailOrURL", EntityTag.Single));
}
}
}
ArrayPool<SplitPoint>.Shared.Return(rentedSplitPoints);
}
finally
{
_lockSpecialCases.ExitReadLock();
}
}
private void AddSplitPoint(ref SplitPoint[] splitPoints, ref int splitPointsCount, int start, int end, SplitPointReason reason)
{
if (splitPoints.Length == splitPointsCount)
{
if(splitPoints.Length == 0)
{
Array.Resize(ref splitPoints, 4);
}
else
{
Array.Resize(ref splitPoints, 2 * splitPoints.Length);
}
}
splitPoints[splitPointsCount] = new SplitPoint(start, end, reason);
splitPointsCount++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static (int index, int len) FindSufix(ReadOnlySpan<char> s)
{
if (s.Length < 2) { return (-1, 0); }
char f = s[s.Length - 1];
char bf = s[s.Length - 2];
if (f == '.')
{
if (s.Length > 3 && s[s.Length - 3] == '°' && (bf == 'C' || bf == 'c' || bf == 'F' || bf == 'f' || bf == 'K' || bf == 'k'))
{
//removes final '.' on a sequence of °[C|c|F|f|K|k].
return (s.Length - 1, 1);
}
else if (char.IsDigit(bf) || char.IsLower(bf) || CharacterClasses.Quotes.Contains(bf) || CharacterClasses.ExtraSufixesCharacters.Contains(bf))
{
if (s.Length < 4)
{
int c = 0, u = 0, l = 0; // Count the number of dots and upper case
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.') c++;
else if (char.IsUpper(s[i])) u++;
else if (char.IsLower(s[i])) l++;
}
if (u == 1 && c == 1 && l < 3) { return (-1, 0); } // Handles abbreviations on the form of Ul. or Ull.
}
//removes final '.' on a sequence of [0-9|a-z|{Quotes}|{Extra}].
return (s.Length - 1, 1);
}
else if (bf == '.')
{
return (s.Length - 1, 1);
}
else if (char.IsLetter(bf) && !char.IsUpper(bf))
{
return (s.Length - 1, 1);
}
else if (s.Length > 2)
{
int c = 0, u = 0, l = 0, n = 0; // Count the number of dots, upper case and numbers
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.') c++;
else if (char.IsUpper(s[i])) u++;
else if (char.IsLower(s[i])) l++;
else if (char.IsDigit(s[i])) n++;
}
if (u == 1 && c == 1 && l < 3 && n == 0) { return (-1, 0); } // Handles abbreviations on the form of Ul. or Ull.
if (n > u) { return (s.Length - 1, 1); }
if (u > c + 1) { return (s.Length - 1, 1); }
}
}
if (char.IsDigit(bf))
{
if ((f == '+' || f == '-' || f == '*' || f == '/'))
{
//Remove the final +-*/ symbol on a sequence of [0-9][+-*/]
return (s.Length - 1, 1);
}
else if (CharacterClasses.CurrencyCharacters.Contains(f))
{
//Remove final currency symbol from [0-9]$
return (s.Length - 1, 1);
}
//TODO: remove unit from [0-9][{units}]
//_units = ('km km² km³ m m² m³ dm dm² dm³ cm cm² cm³ mm mm² mm³ ha µm nm yd in ft '
// 'kg g mg µg t lb oz m/s km/h kmh mph hPa Pa mbar mb MB kb KB gb GB tb '
// 'TB T G M K % км км² км³ м м² м³ дм дм² дм³ см см² см³ мм мм² мм³ нм '
// 'кг г мг м/с км/ч кПа Па мбар Кб КБ кб Мб МБ мб Гб ГБ гб Тб ТБ тб')
}
if (CharacterClasses.PunctuationCharacters.Contains(f))
{
//Remove the final punctuation symbol
return (s.Length - 1, 1);
}
if (CharacterClasses.CloseQuotesCharacters.Contains(f))
{
//Remove the final closing quotes
return (s.Length - 1, 1);
}
return (-1, 0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int FindPrefix(ReadOnlySpan<char> s)
{
if (s.IsEmpty) { return -1; }
char b = s[0];
if (CharacterClasses.HyphenCharacters.Contains(b))
{
if (s.Length > 1 && !char.IsNumber(s[1]))
{
return 0;
}
}
if (b < 256)
{
if (CharacterClasses.ASCIIPrefixesCharacters.Contains(b)) { return 0; }
}
else
{
if (CharacterClasses.OtherPrefixInfixCharacters.Contains(b)) { return 0; }
}
return -1;
}
private static InfixLocationSorter _infixLocationSorter = new();
private sealed class InfixLocationSorter : IComparer<(int index, int length)>
{
public int Compare((int index, int length) x, (int index, int length) y)
{
//.OrderBy(k => k.index).ThenBy(k => k.length).ToList();
var ix = x.index.CompareTo(y.index);
if (ix == 0)
{
return x.length.CompareTo(y.length);
}
else
{
return ix;
}
}
}
private static readonly SplitPointSorter _splitPointSorter = new();
private sealed class SplitPointSorter : IComparer<SplitPoint>
{
public int Compare(SplitPoint x, SplitPoint y)
{
//.OrderBy(s => s.Begin).ThenBy(s => s.End)
var ix = x.Begin.CompareTo(y.Begin);
if (ix == 0)
{
return x.End.CompareTo(y.End);
}
else
{
return ix;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void FindInfix(ReadOnlySpan<char> s, List<(int index, int length)> infixLocation)
{
infixLocation.Clear();
FindInfixNoOrder(s, infixLocation);
infixLocation.Sort(_infixLocationSorter);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void FindInfixNoOrder(ReadOnlySpan<char> s, List<(int index, int length)> infixLocation)
{
//Split any [...] inside a word
int L1 = s.Length - 1;
int index = 0;
for (int i = 1; i < L1; i++)
{
char c = s[i];
if (((c == '.' || c == '-' || c == '_') && s[i + 1] == c) || c == '…')
{
index = i;
if (char.IsLetterOrDigit(s[i - 1]))
{
while (i < (L1 - 1) && s[i + 1] == c) { i++; }
if (i <= L1 && char.IsLetterOrDigit(s[i + 1]))
{
infixLocation.Add((index, i - index + 1));
}
}
}
else if (c == '.')
{
//split any lower [.] Upper
if (char.IsLower(s[i - 1]) && char.IsUpper(s[i + 1]))
{
infixLocation.Add((i, 1));
}
else if (!char.IsLetterOrDigit(s[i + 1])) //split any [.] [NOT LETTER NOR DIGIT]
{
infixLocation.Add((i, 1));
}
}
else
{
//Split any symbol inside a word
if (c < 256 && CharacterClasses.ASCIIInfixCharacters.Contains(c))
{
if (c == ':' && (i + 1 < L1) && s[i + 1] == '/' && s[i + 2] == '/')
{
continue;
}
//if (c == '$')
//{
// if ( && ((i > 0 && char.IsLetter(s[i - 1])) || (i < s.Length && char.IsLetter(s[i + 1])))))
// //Handle exceptio for currency symbols like R$, Z$, $U, TT$, RD$, $b BZ$ . List taken from: http://www.xe.com/symbols.php
// //do nothing with them
//}
//else
//{
infixLocation.Add((i, 1));
//}
}
else if (c > 256 && CharacterClasses.SymbolCharacters.Contains(c))
{
infixLocation.Add((i, 1));
}
}
}
}
public void OptimizeMemory()
{
_customSimpleSpecialCases?.TrimExcess();
_customSpecialCases?.TrimExcess();
}
}
}