-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsymspell.zig
More file actions
1972 lines (1665 loc) · 74.8 KB
/
Copy pathsymspell.zig
File metadata and controls
1972 lines (1665 loc) · 74.8 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
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
// Copyright (c) 2025 Alim Zanibekov
const std = @import("std");
const filter = @import("filter.zig");
const pthash = @import("pthash.zig");
const util = @import("util.zig");
const iterator = @import("iterator.zig");
const bit = @import("bit.zig");
const ef = @import("ef.zig");
/// UTF-8 string type indicator
pub const Utf8 = struct {};
/// SymSpell - wrapper over GenericSymSpell, uses `levenshteinDistance` as a distance function
pub fn SymSpell(
comptime Word: type,
comptime Ctx: type,
comptime wordMaxDistance: fn (ctx: Ctx, str: []const StringElementType(Word)) usize,
) type {
comptime if (!isStringType(Word)) @compileError("Unsupported string type " ++ @typeName(Word));
const T = StringElementType(Word);
const EdT = if (Word == Utf8) u32 else T;
const Func = struct {
inline fn editDistanceBuffer(_: Ctx, buffer: []u32, word1: []const EdT, word2: []const EdT) u32 {
return levenshteinDistance(EdT, u32, buffer, word1, word2);
}
inline fn strLen(_: Ctx, word: []const T) ?usize {
return if (Word == Utf8) std.unicode.utf8CountCodepoints(word) catch null else word.len;
}
};
return GenericSymSpell(Word, Ctx, Func.editDistanceBuffer, Func.strLen, wordMaxDistance, true, true);
}
/// SymSpellDL - wrapper over GenericSymSpell, uses `damerauLevenshteinDistance` as a distance function
pub fn SymSpellDL(
comptime Word: type,
comptime Ctx: type,
comptime wordMaxDistance: fn (ctx: Ctx, str: []const StringElementType(Word)) usize,
) type {
comptime if (!isStringType(Word)) @compileError("Unsupported string type " ++ @typeName(Word));
const T = StringElementType(Word);
const EdT = if (Word == Utf8) u32 else T;
const Func = struct {
inline fn editDistanceBuffer(_: Ctx, buffer: []u32, word1: []const EdT, word2: []const EdT) u32 {
return damerauLevenshteinDistance(EdT, u32, buffer, word1, word2);
}
inline fn strLen(_: Ctx, word: []const T) ?usize {
return if (Word == Utf8) std.unicode.utf8CountCodepoints(word) catch null else word.len;
}
};
return GenericSymSpell(Word, Ctx, Func.editDistanceBuffer, Func.strLen, wordMaxDistance, true, true);
}
/// SymSpell provides a distance function based fuzzy matcher over a dictionary
/// `Word` - slice type of u8, u16, u21, u32 or `Utf8`,
/// `Ctx` - context type for callbacks
/// `wordMaxDistance` - function to get max delete distance for a word
/// `strLen` - function to get string length
/// `compressEdits` - whether to compress the edits index using Elias-Fano compression
/// `bitPackDictRefs` - whether to compress (by bitpacking) the dictionary references
pub fn GenericSymSpell(
comptime Word: type,
comptime Ctx: type,
comptime editDistanceBuffer: edb: {
const T = StringElementType(Word);
if (Word == Utf8) {
break :edb fn (ctx: Ctx, buffer: []u32, word1: []const u32, word2: []const u32) callconv(.@"inline") u32;
} else {
break :edb fn (ctx: Ctx, buffer: []u32, word1: []const T, word2: []const T) callconv(.@"inline") u32;
}
},
comptime strLen: fn (ctx: Ctx, str: []const StringElementType(Word)) callconv(.@"inline") ?usize,
comptime wordMaxDistance: fn (ctx: Ctx, str: []const StringElementType(Word)) usize,
comptime compressEdits: bool,
comptime bitPackDictRefs: bool,
) type {
comptime if (!isStringType(Word)) @compileError("Unsupported string type " ++ @typeName(Word));
const T = StringElementType(Word);
const WordEdit = struct { edit: []T, i_word: u32, count: u32 };
const SortedEditsIterator = struct {
array: []WordEdit,
len: usize,
i: usize = 0,
pub inline fn size(self: *const @This()) usize {
return self.len;
}
pub fn next(self: *@This()) ?[]const T {
if (self.i >= self.array.len) return null;
if (self.i == 0) {
self.i += 1;
return self.array[self.i - 1].edit;
}
while (std.mem.eql(T, self.array[self.i - 1].edit, self.array[self.i].edit)) {
self.i += 1;
}
self.i += 1;
return self.array[self.i - 1].edit;
}
};
const PTHash = pthash.PTHash([]const T, pthash.OptimalMapper(u64));
const EliasFano = ef.EliasFano;
const debug_stats = builtin.is_test;
return struct {
const Self = @This();
pub const editsCompressed = compressEdits;
pub const dictRefsBitPacked = bitPackDictRefs;
pub const Token = struct {
word: []const T,
count: u32,
};
pub const Hit = struct {
word: []const T = &.{},
edit_distance: usize = std.math.maxInt(u32),
delete_distance: usize = std.math.maxInt(u32),
count: u32 = 0,
};
pub const Suggestion = struct {
segmented: []T,
corrected: []T,
distance_sum: u32,
probability_log_sum: f64,
fn init(
allocator: std.mem.Allocator,
segmented: []const T,
corrected: []const T,
distance_sum: u32,
probability_log_sum: f64,
) !@This() {
return @This(){
.segmented = try allocator.dupe(T, segmented),
.corrected = try allocator.dupe(T, corrected),
.distance_sum = distance_sum,
.probability_log_sum = probability_log_sum,
};
}
fn expand(self: *@This(), allocator: std.mem.Allocator, segmented_len: usize, corrected_len: usize, save_data: bool) !void {
if (self.segmented.len == 0 and self.corrected.len == 0) {
self.segmented = try allocator.alloc(T, segmented_len);
self.corrected = try allocator.alloc(T, corrected_len);
} else {
if (save_data) {
self.segmented = try allocator.realloc(self.segmented, segmented_len);
self.corrected = try allocator.realloc(self.corrected, corrected_len);
} else {
self.segmented = allocator.remap(self.segmented, segmented_len) orelse sg: {
allocator.free(self.segmented);
break :sg try allocator.alloc(T, segmented_len);
};
self.corrected = allocator.remap(self.corrected, corrected_len) orelse sg: {
allocator.free(self.corrected);
break :sg try allocator.alloc(T, corrected_len);
};
}
}
}
pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void {
allocator.free(self.segmented);
allocator.free(self.corrected);
}
};
pub const DictStats = struct {
edits_layer_num_max: usize,
edits_num_max: usize,
word_max_len: usize,
word_max_size: usize,
max_distance: usize,
count_sum: usize,
count_uniform: bool,
};
pub const BloomOptions = struct {
fp_rate: f64, // False positive rate
dict_stats: ?DictStats = null,
};
pub const LRUOptions = struct {
capacity: u32, // LRU hash map capacity
dict_stats: ?DictStats = null,
};
dict: []const Token,
dict_stats: DictStats,
pthash: PTHash.Type,
edits_index: if (compressEdits) EliasFano else []u32,
edits_values: if (bitPackDictRefs) bit.BitArray else []u32,
punctuation: []const []const T = &.{ ",", "]", "[", ")", "(", "}", "{", "." },
separators: []const []const T = &.{" "},
segmentation_token: []const T = " ",
ctx: Ctx,
// Used when dict was allocated by `readFrom`. Arena for words
dict_data: ?[]const T = null,
assume_ed_increases: bool = true,
pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
self.pthash.deinit(allocator);
if (compressEdits) {
self.edits_index.deinit(allocator);
} else {
allocator.free(self.edits_index);
}
if (bitPackDictRefs) {
self.edits_values.deinit(allocator);
} else {
allocator.free(self.edits_values);
}
if (self.dict_data) |dd| {
allocator.free(dd);
allocator.free(self.dict);
}
self.* = undefined;
}
/// Writes the dictionary and index to a binary stream
pub fn writeTo(self: *const Self, writer: *std.Io.Writer) !void {
const dict_len: u64 = @intCast(self.dict.len);
try writer.writeAll(std.mem.asBytes(&dict_len));
var data_len: u64 = 0;
for (self.dict) |token| data_len += @intCast(token.word.len);
try writer.writeAll(std.mem.asBytes(&data_len));
for (self.dict) |token| try writer.writeAll(std.mem.sliceAsBytes(token.word));
for (self.dict) |token| try writer.writeAll(std.mem.asBytes(&token.count));
for (self.dict) |token| {
const word_len: u32 = @intCast(token.word.len);
try writer.writeAll(std.mem.asBytes(&word_len));
}
try writer.writeAll(std.mem.asBytes(&self.dict_stats));
try self.pthash.writeTo(writer);
if (compressEdits) {
try self.edits_index.writeTo(writer);
} else {
const ei_len: u64 = @intCast(self.edits_index.len);
try writer.writeAll(std.mem.asBytes(&ei_len));
try writer.writeAll(std.mem.sliceAsBytes(self.edits_index));
}
if (bitPackDictRefs) {
try self.edits_values.writeTo(writer);
} else {
const ev_len: u64 = @intCast(self.edits_values.len);
try writer.writeAll(std.mem.asBytes(&ev_len));
try writer.writeAll(std.mem.sliceAsBytes(self.edits_values));
}
const ae: u8 = if (self.assume_ed_increases) 1 else 0;
try writer.writeAll(std.mem.asBytes(&ae));
}
/// Reads the dictionary and index from a binary stream
/// Owns the deserialized dict
pub fn readFrom(allocator: std.mem.Allocator, reader: *std.Io.Reader, ctx: Ctx) !Self {
var dict_len: u64 = undefined;
try reader.readSliceAll(std.mem.asBytes(&dict_len));
const n: usize = @intCast(dict_len);
var data_len: u64 = undefined;
try reader.readSliceAll(std.mem.asBytes(&data_len));
const dict_data = try allocator.alloc(T, @intCast(data_len));
errdefer allocator.free(dict_data);
try reader.readSliceAll(std.mem.sliceAsBytes(dict_data));
const dict = try allocator.alloc(Token, n);
errdefer allocator.free(dict);
for (dict) |*token| try reader.readSliceAll(std.mem.asBytes(&token.count));
var offset: usize = 0;
for (dict) |*token| {
var word_len: u32 = undefined;
try reader.readSliceAll(std.mem.asBytes(&word_len));
token.word = dict_data[offset .. offset + word_len];
offset += word_len;
}
var dict_stats: DictStats = undefined;
try reader.readSliceAll(std.mem.asBytes(&dict_stats));
var ph = try PTHash.Type.readFrom(allocator, reader);
errdefer ph.deinit(allocator);
var edits_index: if (compressEdits) EliasFano else []u32 = undefined;
if (compressEdits) {
edits_index = try EliasFano.readFrom(allocator, reader);
} else {
var ei_len: u64 = undefined;
try reader.readSliceAll(std.mem.asBytes(&ei_len));
edits_index = try allocator.alloc(u32, @intCast(ei_len));
try reader.readSliceAll(std.mem.sliceAsBytes(edits_index));
}
var edits_values: if (bitPackDictRefs) bit.BitArray else []u32 = undefined;
if (bitPackDictRefs) {
edits_values = try bit.BitArray.readFrom(allocator, reader);
} else {
var ev_len: u64 = undefined;
try reader.readSliceAll(std.mem.asBytes(&ev_len));
edits_values = try allocator.alloc(u32, @intCast(ev_len));
try reader.readSliceAll(std.mem.sliceAsBytes(edits_values));
}
var ae: u8 = undefined;
try reader.readSliceAll(std.mem.asBytes(&ae));
return Self{
.dict = dict,
.dict_data = dict_data,
.dict_stats = dict_stats,
.pthash = ph,
.edits_index = edits_index,
.edits_values = edits_values,
.ctx = ctx,
.assume_ed_increases = ae == 1,
};
}
/// Collects statistics from the input dictionary.
/// These stats are used to size buffers, etc
pub fn getDictStats(ctx: Ctx, dict: []const Token) !DictStats {
var edits_layer_num_max: usize = 1;
var edits_num_max: usize = 1;
var word_max_size: usize = 1;
var word_max_len: usize = 1;
var max_distance: usize = 0;
var count_sum: usize = 0;
var count_max: u32 = 0;
var tm = if (debug_stats) util.TimeMasurer{ .io = std.testing.io } else (struct {
pub inline fn start(_: *@This()) void {}
pub inline fn loop(_: *@This(), _: []const u8) void {}
}){};
tm.start();
for (dict) |it| {
word_max_size = @max(word_max_size, it.word.len);
const len = strLen(ctx, it.word) orelse return error.GetWordLengthError;
word_max_len = @max(word_max_len, len);
const distance = wordMaxDistance(ctx, it.word);
max_distance = @max(max_distance, distance);
const bin = binomial(len, distance);
edits_layer_num_max = @max(edits_layer_num_max, bin);
edits_num_max = @max(edits_num_max, maxDeletes(len, distance - 1) + bin);
count_sum += it.count;
count_max = @max(it.count, count_max);
}
tm.loop("Dict stats calculation");
return DictStats{
.edits_layer_num_max = edits_layer_num_max,
.edits_num_max = edits_num_max,
.word_max_size = word_max_size,
.word_max_len = word_max_len,
.max_distance = max_distance,
.count_sum = count_sum,
.count_uniform = (dict.len > 0) and count_max == dict[0].count,
};
}
/// Constructs SymSpell using a Bloom filter for deletes deduplication
/// `BloomOptions`.`fp_rate` - false positive rate for Bloom filter
pub fn initBloom(allocator: std.mem.Allocator, seed: u64, dict: []const Token, ctx: Ctx, opts: BloomOptions) !Self {
const stats = if (opts.dict_stats) |it| it else try getDictStats(ctx, dict);
const byte_count: usize = @intCast(filter.bloomByteSize(stats.edits_num_max, opts.fp_rate));
var deduper = try BloomDeduper(T).init(allocator, byte_count, opts.fp_rate);
defer deduper.deinit();
return init(allocator, seed, dict, ctx, stats, @TypeOf(&deduper), &deduper);
}
/// Constructs SymSpell using an LRU cache for edit deduplication
/// `LRUOptions`.`capacity` - LRU cache capacity
pub fn initLRU(allocator: std.mem.Allocator, seed: u64, dict: []const Token, ctx: Ctx, opts: LRUOptions) !Self {
const stats = if (opts.dict_stats) |it| it else getDictStats(ctx, dict);
const deduper = try LRUDeduper(T).init(allocator, opts.capacity);
defer deduper.deinit();
return init(allocator, seed, dict, ctx, stats, @TypeOf(&deduper), &deduper);
}
/// Builds SymSpell dictionary using the provided deduper
/// `seed` is uses for the PTHash build, on error.Collision retry with a different one
pub fn init(
main_allocator: std.mem.Allocator,
seed: u64,
dict: []const Token,
ctx: Ctx,
dict_stats: DictStats,
Deduper: type,
deduper: Deduper,
) !Self {
var tm = if (debug_stats) util.TimeMasurer{ .io = testing.io } else (struct {
pub inline fn start(_: *@This()) void {}
pub inline fn loop(_: *@This(), _: []const u8) void {}
}){};
var arena_allocator = std.heap.ArenaAllocator.init(main_allocator);
defer arena_allocator.deinit();
const arena = arena_allocator.allocator();
tm.start();
var word_edits = try std.ArrayListUnmanaged(WordEdit).initCapacity(arena, dict.len);
var generator = try EditsGenerator(Word, @TypeOf(deduper)).init(arena, dict_stats.word_max_size);
for (dict, 0..) |it, i| {
try generator.load(it.word, wordMaxDistance(ctx, it.word), deduper);
while (generator.next()) {
const str = try arena.dupe(T, generator.getValue());
try word_edits.append(arena, WordEdit{
.i_word = @intCast(i),
.count = it.count,
.edit = str,
});
}
}
tm.loop("Deletes generation");
std.mem.sort(WordEdit, word_edits.items, {}, struct {
fn func(_: void, a: WordEdit, b: WordEdit) bool {
const order = std.mem.order(T, a.edit, b.edit);
if (order == .eq) return a.i_word < b.i_word;
return order == .lt;
}
}.func);
tm.loop("Word deletes sort");
var unique: usize = 1;
for (1..word_edits.items.len) |i| {
if (!std.mem.eql(T, word_edits.items[i].edit, word_edits.items[i - 1].edit)) unique += 1;
}
tm.loop("Counting unique deletes");
var iter = SortedEditsIterator{ .array = word_edits.items, .len = unique };
var ph = try PTHash.buildSeed(main_allocator, @TypeOf(&iter), &iter, PTHash.buildConfig(iter.size(), .{
.lambda = 6,
.alpha = 0.97,
.max_bucket_size = 512,
// .minimal = true,
}), seed);
tm.loop("Build PTHash");
errdefer ph.deinit(main_allocator);
var word_edits_groups = try arena.alloc([]WordEdit, ph.size());
@memset(word_edits_groups, &.{});
var start_i: usize = 0;
var prev_idx = try ph.get(word_edits.items[0].edit);
var edits_values_size: usize = 1;
// Sort word_edits in EliasFano compressible order, also allows to not have to store counts
for (1..word_edits.items.len) |i| {
const hash = try ph.get(word_edits.items[i].edit);
if (hash == prev_idx) {
if (word_edits.items[i].i_word != word_edits.items[i - 1].i_word) edits_values_size += 1;
continue;
}
edits_values_size += 1;
word_edits_groups[prev_idx] = word_edits.items[start_i..i];
start_i = i;
prev_idx = hash;
}
word_edits_groups[prev_idx] = word_edits.items[start_i..];
tm.loop("Group deletes");
var edits_index = try (if (compressEdits) arena else main_allocator).alloc(u32, ph.size() + 1);
const id_width = std.math.log2_int_ceil(usize, dict.len);
var edits_values = if (bitPackDictRefs)
try bit.BitArray.initCapacity(main_allocator, id_width * (edits_values_size + 1))
else
try main_allocator.alloc(u32, edits_values_size + 1);
errdefer {
if (bitPackDictRefs) edits_values.deinit(main_allocator) else main_allocator.free(edits_values);
}
@memset(edits_index, 0);
if (!bitPackDictRefs) @memset(edits_values, 0);
tm.loop("Prepare buffers");
var j: u32 = 0;
var last_hash: u64 = 0;
for (word_edits_groups, 0..) |group, hash| {
if (group.len == 0) {
// for EliasFano
edits_index[hash] = j;
continue;
}
last_hash = hash;
edits_index[hash] = j;
// If we sort edits_values for a group based on count, we can early terminate in Searcher
// when we already find a word (in edits_values) with the theoretically lowest edit distance for
// the current delete distance
std.mem.sort(WordEdit, group, {}, struct {
fn func(_: void, a: WordEdit, b: WordEdit) bool {
return a.count > b.count;
}
}.func);
if (comptime bitPackDictRefs) {
edits_values.appendUIntAssumeCapacity(group[0].i_word, @intCast(id_width));
} else {
edits_values[j] = group[0].i_word;
}
j += 1;
for (1..group.len) |k| {
if (group[k].i_word == group[k - 1].i_word) continue;
if (comptime bitPackDictRefs) {
edits_values.appendUIntAssumeCapacity(group[k].i_word, @intCast(id_width));
} else {
edits_values[j] = group[k].i_word;
}
j += 1;
}
}
// enclosing element to simplify `getEditsIndexAndSize`
for ((last_hash + 1)..(ph.size() + 1)) |i| edits_index[i] = j;
tm.loop("Build deletes index");
if (compressEdits) {
var ef_iter = (struct {
array: []const u32,
i: isize = 0,
pub fn size(self: *const @This()) usize {
return self.array.len;
}
pub fn next(self: *@This()) ?u64 {
if (self.i >= self.array.len) return null;
const res = self.array[@intCast(self.i)];
self.i += 1;
return @intCast(res);
}
pub fn reset(self: *@This()) void {
self.i = 0;
}
}){ .array = edits_index };
const edits_index_ef = try EliasFano.init(main_allocator, edits_index[edits_index.len - 1], @TypeOf(&ef_iter), &ef_iter);
// errdefer edits_index_ef.deinit(main_allocator);
tm.loop("Compress deletes index");
return Self{
.pthash = ph,
.edits_values = edits_values,
.edits_index = edits_index_ef,
.dict = dict,
.dict_stats = dict_stats,
.ctx = ctx,
};
} else {
return Self{
.pthash = ph,
.edits_values = edits_values,
.edits_index = edits_index,
.dict = dict,
.dict_stats = dict_stats,
.ctx = ctx,
};
}
}
/// Reusable search instance tied to a specific SymSpell dictionary
pub fn Searcher(EditsDeduper: type) type {
return struct {
sym_spell: *const Self,
word: []const T,
seen: std.AutoHashMap(u32, void),
generator: EditsGenerator(Word, EditsDeduper),
len: usize,
max_distance: usize,
hit: Hit,
ed_buffer: []u32,
ed_buffer_1: if (Word == Utf8) []u32 else void,
ed_buffer_2: if (Word == Utf8) []u32 else void,
/// Allocates the search buffers and internal state
pub fn init(sym_spell: *const Self, allocator: std.mem.Allocator) !@This() {
const generator = try EditsGenerator(Word, EditsDeduper)
.init(
allocator,
sym_spell.dict_stats.word_max_size + sym_spell.dict_stats.max_distance * 4, // * 4 in case of utf8
);
var seen = std.AutoHashMap(u32, void).init(allocator);
try seen.ensureUnusedCapacity(@min(sym_spell.dict_stats.edits_num_max, 4096)); // magic number, I'm sorry
const max_input_len = sym_spell.dict_stats.word_max_len + sym_spell.dict_stats.max_distance;
const max_saved_len = sym_spell.dict_stats.word_max_len;
return .{
.len = undefined,
.word = undefined,
.max_distance = undefined,
.hit = Hit{},
.ed_buffer = try allocator.alloc(u32, (max_input_len + 1) * (max_saved_len + 1)),
.ed_buffer_1 = if (Word == Utf8) try allocator.alloc(u32, max_saved_len) else undefined,
.ed_buffer_2 = if (Word == Utf8) try allocator.alloc(u32, max_input_len) else undefined,
.seen = seen,
.sym_spell = sym_spell,
.generator = generator,
};
}
pub fn deinit(self: *@This(), allocator: std.mem.Allocator) void {
allocator.free(self.ed_buffer);
if (Word == Utf8) {
allocator.free(self.ed_buffer_1);
allocator.free(self.ed_buffer_2);
}
self.seen.deinit();
self.generator.deinit(allocator);
}
/// Initializes the search with a given input word
pub fn load(self: *@This(), word: []const T, max_distance: usize, edits_deduper: EditsDeduper) !void {
const len = strLen(self.sym_spell.ctx, word) orelse return error.GetWordLengthError;
if (len > self.sym_spell.dict_stats.word_max_len + self.sym_spell.dict_stats.max_distance) {
// no chances to find something useful
self.generator.reset();
self.len = 0;
return;
}
self.hit = Hit{};
self.word = word;
self.len = len;
self.max_distance = max_distance;
self.seen.clearRetainingCapacity();
try self.generator.load(word, self.max_distance, edits_deduper);
}
fn getEditDistance(self: *@This(), str1: []const T, str2: []const T) !u32 {
if (Word == Utf8) {
const s1 = try utf8ToU32OnBuffer(self.ed_buffer_1, str1);
const s2 = try utf8ToU32OnBuffer(self.ed_buffer_2, str2);
return editDistanceBuffer(self.sym_spell.ctx, self.ed_buffer, s1, s2);
} else {
return editDistanceBuffer(self.sym_spell.ctx, self.ed_buffer, str1, str2);
}
}
/// Advances the iterator and attempts to find the next closest matching word in the dictionary
/// Returns true if a new best hit was found
/// `Searcher`.`hit` is valid until the next call
pub fn next(self: *@This()) !bool {
const id_width = if (bitPackDictRefs) std.math.log2_int_ceil(usize, self.sym_spell.dict.len) else {};
var delete_distance: usize = 0;
while (self.generator.next()) {
const gen_token = self.generator.getValue();
const hash = try self.sym_spell.pthash.get(gen_token);
const ias = try self.sym_spell.getEditsIndexAndSize(hash);
{
const word_i = if (bitPackDictRefs)
try self.sym_spell.edits_values.getVar(usize, id_width, ias.index * id_width)
else
self.sym_spell.edits_values[ias.index];
const word = self.sym_spell.dict[word_i].word;
if (!containsInOrder(T, word, gen_token)) continue;
}
for ((ias.index + 1)..(ias.index + 1 + ias.size)) |i| {
const word_i = if (bitPackDictRefs)
try self.sym_spell.edits_values.getVar(usize, id_width, i * id_width)
else
self.sym_spell.edits_values[i];
const it = self.sym_spell.dict[word_i];
if (@abs(@as(i64, @intCast(strLen(self.sym_spell.ctx, it.word))) - @as(i64, @intCast(self.len))) > self.max_distance) {
continue;
}
if (self.seen.contains(word_i)) continue;
try self.seen.put(word_i, {});
const actual_distance = try self.getEditDistance(it.word, gen_token);
if (actual_distance <= self.max_distance) {
self.hit = .{
.count = it.count,
.word = it.word,
.edit_distance = actual_distance,
.delete_distance = delete_distance,
};
return true;
}
}
delete_distance = self.generator.current_distance;
}
return false;
}
/// Returns the best match for a term
pub fn top(self: *@This()) !?Hit {
const id_width = if (bitPackDictRefs) std.math.log2_int_ceil(usize, self.sym_spell.dict.len) else {};
var best_hit = Hit{};
var delete_distance: usize = 0;
while (self.generator.next()) {
if (self.sym_spell.assume_ed_increases and delete_distance > best_hit.delete_distance) {
break;
}
const gen_token = self.generator.getValue();
const hash = try self.sym_spell.pthash.get(gen_token);
const ias = try self.sym_spell.getEditsIndexAndSize(hash);
if (ias.size == 0) continue;
{
const word_i = if (bitPackDictRefs)
try self.sym_spell.edits_values.getVar(usize, id_width, ias.index * id_width)
else
self.sym_spell.edits_values[ias.index];
const word = self.sym_spell.dict[word_i].word;
if (!containsInOrder(T, word, gen_token)) continue;
}
for ((ias.index)..(ias.index + ias.size)) |i| {
const word_i = if (bitPackDictRefs)
try self.sym_spell.edits_values.getVar(usize, id_width, i * id_width)
else
self.sym_spell.edits_values[i];
const it = self.sym_spell.dict[word_i];
const str_len = strLen(self.sym_spell.ctx, it.word) orelse return error.GetWordLengthError;
if (@abs(@as(i64, @intCast(str_len)) - @as(i64, @intCast(self.len))) > self.max_distance) {
continue;
}
// edits_values for a specific word are ordered by count
// when best_hit.edit_distance == best_hit.delete_distance we have already found the minimal edit distance
if (self.sym_spell.assume_ed_increases and
best_hit.edit_distance == best_hit.delete_distance and
it.count < best_hit.count) break;
if (self.seen.contains(@intCast(word_i))) continue;
try self.seen.put(@intCast(word_i), {});
const actual_distance = try self.getEditDistance(it.word, gen_token);
if (actual_distance <= self.max_distance and
(actual_distance < best_hit.edit_distance or
(actual_distance == best_hit.edit_distance and it.count > best_hit.count)))
{
best_hit = .{
.count = it.count,
.word = it.word,
.edit_distance = actual_distance,
.delete_distance = delete_distance,
};
if (best_hit.edit_distance == 0) {
return best_hit; // can't do better, exact match
}
}
}
delete_distance = self.generator.current_distance;
}
if (best_hit.word.len > 0) return best_hit;
return null;
}
};
}
pub fn getEditsIndexAndSize(self: *const Self, hash: u64) !struct { index: usize, size: usize } {
if (compressEdits) {
const index = try self.edits_index.get(hash);
const index_next = try self.edits_index.get(hash + 1);
return .{ .index = index, .size = index_next - index };
} else {
const index = self.edits_index[hash];
const index_next = self.edits_index[hash + 1];
return .{ .index = index, .size = index_next - index };
}
}
pub fn isStartsWithPunctuation(self: *const Self, str: []const T) ?usize {
for (self.punctuation) |sp| {
if (std.mem.startsWith(u8, str, sp)) {
return sp.len;
}
}
return null;
}
pub fn isStartsWithSeparator(self: *const Self, str: []const T) ?usize {
for (self.separators) |sp| {
if (std.mem.startsWith(u8, str, sp)) {
return sp.len;
}
}
return null;
}
/// Attempts to split and correct a possibly misspelled phrase
pub fn wordSegmentation(self: *const Self, allocator: std.mem.Allocator, input: []const T) !?Suggestion {
const input_len = strLen(self.ctx, input) orelse return error.GetWordLengthError;
const word_max_size = self.dict_stats.word_max_size + self.dict_stats.max_distance * 4;
const word_max_len = self.dict_stats.word_max_len + self.dict_stats.max_distance;
const suggestions_count = @min(word_max_len, input_len);
var suggestions = try allocator.alloc(Suggestion, suggestions_count);
errdefer allocator.free(suggestions);
errdefer for (suggestions) |*s| s.deinit(allocator);
for (suggestions) |*s| s.* = .{ .segmented = &.{}, .corrected = &.{}, .distance_sum = 0, .probability_log_sum = 0.0 };
var circular_index: isize = -1;
var searcher = try Self.Searcher(NoopDeduper(u8)).init(self, allocator);
defer searcher.deinit(allocator);
var buffer_1 = try allocator.alloc(T, word_max_size);
defer allocator.free(buffer_1);
var buffer_2 = try allocator.alloc(T, word_max_size);
defer allocator.free(buffer_2);
const space = self.segmentation_token;
var start: usize = 0;
for (0..input_len) |j| {
const max_len = @min(word_max_len, input_len - j);
var end: usize = start;
for (1..(max_len + 1)) |i| {
if (T == Utf8) {
end += try std.unicode.utf8ByteSequenceLength(input[end]);
} else {
end += 1;
}
var str = input[start..end];
var separator_length: usize = 0;
var top_probability_log: f64 = std.math.nan(f64);
var top_ed: usize = 0;
var k: usize = 0;
var str_len: usize = 0;
if (self.isStartsWithSeparator(str)) |sp| {
str = str[sp..];
} else {
separator_length += 1;
}
if (T == Utf8) {
var pos: usize = 0;
while (pos < str.len) {
if (self.isStartsWithSeparator(str[pos..]) orelse self.isStartsWithPunctuation(str[pos..])) |sp| {
top_ed += sp;
pos += sp;
continue;
}
str_len += 1;
const cp_len = std.unicode.utf8ByteSequenceLength(str[pos]) catch unreachable;
@memcpy(buffer_1[k..(k + cp_len)], str[pos..(pos + cp_len)]);
pos += cp_len;
k += cp_len;
}
} else {
var pos: usize = 0;
while (pos < str.len) {
if (self.isStartsWithSeparator(str[pos..]) orelse self.isStartsWithPunctuation(str[pos..])) |sp| {
top_ed += sp;
pos += sp;
continue;
}
str_len += 1;
buffer_1[k] = str[pos];
pos += 1;
k += 1;
}
}
const part_length = str_len;
const part = buffer_1[0..k];
try searcher.load(part, wordMaxDistance(self.ctx, part), NoopDeduper(u8){});
var best_hit_ed: usize = std.math.maxInt(usize);
var best_hit_dd: usize = std.math.maxInt(usize);
var best_hit_word: []const T = &.{};
var best_hit_count: u32 = 0;
if (try searcher.top()) |top| {
const word = top.word;
@memcpy(buffer_2[0..word.len], word);
best_hit_word = buffer_2[0..word.len];
best_hit_ed = top.edit_distance;
best_hit_count = top.count;
best_hit_dd = top.delete_distance;
}
var top_result: []const T = undefined;
if (best_hit_word.len == 0) {
top_ed += part_length;
top_result = part;
top_probability_log = std.math.log10(10.0 / (@as(f64, @floatFromInt(self.dict_stats.count_sum)) * std.math.pow(f64, @floatFromInt(part_length), 10.0)));
} else {
top_ed += best_hit_ed;
top_result = best_hit_word;
top_probability_log = std.math.log10(@as(f64, @floatFromInt(best_hit_count)) / @as(f64, @floatFromInt(self.dict_stats.count_sum)));
}
if (j == 0) {
suggestions[(i - 1) % suggestions_count] = try Suggestion.init(allocator, part, top_result, @intCast(top_ed), top_probability_log);
} else {
const c: usize = @intCast(circular_index);
const d: usize = (i + @as(usize, @intCast(circular_index))) % suggestions_count;
if (i == word_max_len or ((suggestions[c].distance_sum + top_ed == suggestions[d].distance_sum or
suggestions[c].distance_sum + separator_length + top_ed == suggestions[d].distance_sum) and
(suggestions[d].probability_log_sum < suggestions[c].probability_log_sum + top_probability_log)) or
suggestions[c].distance_sum + separator_length + top_ed < suggestions[d].distance_sum)
{
const n_1 = suggestions[c].segmented.len + space.len + part.len;
const n_2 = suggestions[c].corrected.len + space.len + top_result.len;
if (d == c) {
const start_1 = suggestions[d].segmented.len;
const start_2 = suggestions[d].corrected.len;
try suggestions[d].expand(allocator, n_1, n_2, true);
memcpuMultiple(T, suggestions[d].segmented[start_1..], &.{ space, part });
memcpuMultiple(T, suggestions[d].corrected[start_2..], &.{ space, top_result });
} else {
try suggestions[d].expand(allocator, n_1, n_2, false);
memcpuMultiple(T, suggestions[d].segmented, &.{ suggestions[c].segmented, space, part });
memcpuMultiple(T, suggestions[d].corrected, &.{ suggestions[c].corrected, space, top_result });
}
suggestions[d].distance_sum = suggestions[c].distance_sum + @as(u32, @intCast(separator_length + top_ed));
suggestions[d].probability_log_sum = suggestions[c].probability_log_sum + top_probability_log;
}
}
}
if (T == Utf8) {
start += try std.unicode.utf8ByteSequenceLength(input[start]);
} else {
start += 1;
}
circular_index += 1;
if (circular_index >= suggestions_count)
circular_index = 0;
}
for (suggestions, 0..) |*s, j| {
if (j != @as(usize, @intCast(circular_index))) s.deinit(allocator);
}
if (circular_index != -1) {
const copy = suggestions[@intCast(circular_index)];
allocator.free(suggestions);
return copy;
} else {
allocator.free(suggestions);
return null;
}
}
};
}
/// Does nothing, always allows all edits
pub fn NoopDeduper(comptime T: type) type {
stringBackingTypeGuard(T);
return struct {