forked from apache/lucenenet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFreeTextSuggester.cs
More file actions
886 lines (772 loc) · 35.6 KB
/
Copy pathFreeTextSuggester.cs
File metadata and controls
886 lines (772 loc) · 35.6 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
using J2N.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Shingle;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Codecs;
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Store;
using Lucene.Net.Util;
using Lucene.Net.Util.Fst;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Directory = Lucene.Net.Store.Directory;
using JCG = J2N.Collections.Generic;
using Int64 = J2N.Numerics.Int64;
namespace Lucene.Net.Search.Suggest.Analyzing
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TODO
// - test w/ syns
// - add pruning of low-freq ngrams?
/// <summary>
/// Builds an ngram model from the text sent to <see cref="Build(IInputEnumerator, double)"/>
/// and predicts based on the last grams-1 tokens in
/// the request sent to <see cref="DoLookup(string, IEnumerable{BytesRef}, bool, int, CancellationToken)"/>. This tries to
/// handle the "long tail" of suggestions for when the
/// incoming query is a never before seen query string.
///
/// <para>Likely this suggester would only be used as a
/// fallback, when the primary suggester fails to find
/// any suggestions.
///
/// </para>
/// <para>Note that the weight for each suggestion is unused,
/// and the suggestions are the analyzed forms (so your
/// analysis process should normally be very "light").
///
/// </para>
/// <para>This uses the stupid backoff language model to smooth
/// scores across ngram models; see
/// <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.76.1126">
/// "Large language models in machine translation"</a> for details.
///
/// </para>
/// <para> From <see cref="DoLookup(string, IEnumerable{BytesRef}, bool, int, CancellationToken)"/>, the key of each result is the
/// ngram token; the value is <see cref="long.MaxValue"/> * score (fixed
/// point, cast to long). Divide by <see cref="long.MaxValue"/> to get
/// the score back, which ranges from 0.0 to 1.0.
///
/// <c>onlyMorePopular</c> is unused.
///
/// @lucene.experimental
/// </para>
/// </summary>
public class FreeTextSuggester : Lookup
{
/// <summary>
/// Codec name used in the header for the saved model. </summary>
public const string CODEC_NAME = "freetextsuggest";
/// <summary>
/// Initial version of the the saved model file format. </summary>
public const int VERSION_START = 0;
/// <summary>
/// Current version of the the saved model file format. </summary>
public const int VERSION_CURRENT = VERSION_START;
/// <summary>
/// By default we use a bigram model. </summary>
public const int DEFAULT_GRAMS = 2;
// In general this could vary with gram, but the
// original paper seems to use this constant:
/// <summary>
/// The constant used for backoff smoothing; during
/// lookup, this means that if a given trigram did not
/// occur, and we backoff to the bigram, the overall score
/// will be 0.4 times what the bigram model would have
/// assigned.
/// </summary>
public const double ALPHA = 0.4;
/// <summary>
/// Holds 1gram, 2gram, 3gram models as a single FST. </summary>
private FST<Int64> fst;
/// <summary>
/// Analyzer that will be used for analyzing suggestions at
/// index time.
/// </summary>
private readonly Analyzer indexAnalyzer;
private long totTokens;
/// <summary>
/// Analyzer that will be used for analyzing suggestions at
/// query time.
/// </summary>
private readonly Analyzer queryAnalyzer;
// 2 = bigram, 3 = trigram
private readonly int grams;
private readonly byte separator;
/// <summary>
/// Number of entries the lookup was built with </summary>
private long count = 0;
/// <summary>
/// The default character used to join multiple tokens
/// into a single ngram token. The input tokens produced
/// by the analyzer must not contain this character.
/// </summary>
public const byte DEFAULT_SEPARATOR = 0x1e;
/// <summary>
/// Instantiate, using the provided analyzer for both
/// indexing and lookup, using bigram model by default.
/// </summary>
public FreeTextSuggester(Analyzer analyzer)
: this(analyzer, analyzer, DEFAULT_GRAMS)
{
}
/// <summary>
/// Instantiate, using the provided indexing and lookup
/// analyzers, using bigram model by default.
/// </summary>
public FreeTextSuggester(Analyzer indexAnalyzer, Analyzer queryAnalyzer)
: this(indexAnalyzer, queryAnalyzer, DEFAULT_GRAMS)
{
}
/// <summary>
/// Instantiate, using the provided indexing and lookup
/// analyzers, with the specified model (2
/// = bigram, 3 = trigram, etc.).
/// </summary>
public FreeTextSuggester(Analyzer indexAnalyzer, Analyzer queryAnalyzer, int grams)
: this(indexAnalyzer, queryAnalyzer, grams, DEFAULT_SEPARATOR)
{
}
/// <summary>
/// Instantiate, using the provided indexing and lookup
/// analyzers, and specified model (2 = bigram, 3 =
/// trigram ,etc.). The <paramref name="separator"/> is passed to <see cref="ShingleFilter.SetTokenSeparator(string)"/>
/// to join multiple
/// tokens into a single ngram token; it must be an ascii
/// (7-bit-clean) byte. No input tokens should have this
/// byte, otherwise <see cref="ArgumentException"/> is
/// thrown.
/// </summary>
public FreeTextSuggester(Analyzer indexAnalyzer, Analyzer queryAnalyzer, int grams, byte separator)
{
this.grams = grams;
this.indexAnalyzer = AddShingles(indexAnalyzer);
this.queryAnalyzer = AddShingles(queryAnalyzer);
if (grams < 1)
{
throw new ArgumentOutOfRangeException(nameof(grams), "grams must be >= 1"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
if ((separator & 0x80) != 0)
{
throw new ArgumentOutOfRangeException(nameof(separator), "separator must be simple ascii character"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
}
this.separator = separator;
}
/// <summary>
/// Returns byte size of the underlying FST. </summary>
public override long GetSizeInBytes()
{
if (fst is null)
{
return 0;
}
return fst.GetSizeInBytes();
}
// LUCENENET specific - removed AnalyzingComparer because it is not in use.
private Analyzer AddShingles(Analyzer other)
{
if (grams == 1)
{
return other;
}
else
{
// TODO: use ShingleAnalyzerWrapper?
// Tack on ShingleFilter to the end, to generate token ngrams:
return new AnalyzerWrapperAnonymousClass(this, other.Strategy, other);
}
}
private sealed class AnalyzerWrapperAnonymousClass : AnalyzerWrapper
{
private readonly FreeTextSuggester outerInstance;
private readonly Analyzer other;
public AnalyzerWrapperAnonymousClass(FreeTextSuggester outerInstance, ReuseStrategy reuseStrategy, Analyzer other)
: base(reuseStrategy)
{
this.outerInstance = outerInstance;
this.other = other;
}
protected override Analyzer GetWrappedAnalyzer(string fieldName)
{
return other;
}
protected override TokenStreamComponents WrapComponents(string fieldName, TokenStreamComponents components)
{
ShingleFilter shingles = new ShingleFilter(components.TokenStream, 2, outerInstance.grams);
shingles.SetTokenSeparator(char.ToString((char)outerInstance.separator));
return new TokenStreamComponents(components.Tokenizer, shingles);
}
}
public override void Build(IInputEnumerator enumerator)
{
Build(enumerator, IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB);
}
/// <summary>
/// Build the suggest index, using up to the specified
/// amount of temporary RAM while building. Note that
/// the weights for the suggestions are ignored.
/// </summary>
public virtual void Build(IInputEnumerator enumerator, double ramBufferSizeMB)
{
// LUCENENET: Added guard clause for null
if (enumerator is null)
throw new ArgumentNullException(nameof(enumerator));
if (enumerator.HasPayloads)
{
throw new ArgumentException("this suggester doesn't support payloads");
}
if (enumerator.HasContexts)
{
throw new ArgumentException("this suggester doesn't support contexts");
}
string prefix = this.GetType().Name;
var directory = OfflineSorter.DefaultTempDir;
// LUCENENET specific - using GetRandomFileName() instead of picking a random int
DirectoryInfo tempIndexPath; // LUCENENET: IDE0059: Remove unnecessary value assignment
while (true)
{
tempIndexPath = new DirectoryInfo(Path.Combine(directory, prefix + ".index." + Path.GetFileNameWithoutExtension(Path.GetRandomFileName())));
tempIndexPath.Create();
if (System.IO.Directory.Exists(tempIndexPath.FullName))
{
break;
}
}
Directory dir = FSDirectory.Open(tempIndexPath);
try
{
#pragma warning disable 612, 618
IndexWriterConfig iwc = new IndexWriterConfig(LuceneVersion.LUCENE_CURRENT, indexAnalyzer);
#pragma warning restore 612, 618
iwc.SetOpenMode(OpenMode.CREATE);
iwc.SetRAMBufferSizeMB(ramBufferSizeMB);
IndexWriter writer = new IndexWriter(dir, iwc);
var ft = new FieldType(TextField.TYPE_NOT_STORED);
// TODO: if only we had IndexOptions.TERMS_ONLY...
ft.IndexOptions = IndexOptions.DOCS_AND_FREQS;
ft.OmitNorms = true;
ft.Freeze();
Document doc = new Document();
Field field = new Field("body", "", ft);
doc.Add(field);
totTokens = 0;
IndexReader reader = null;
bool success = false;
count = 0;
try
{
while (enumerator.MoveNext())
{
BytesRef surfaceForm = enumerator.Current;
field.SetStringValue(surfaceForm.Utf8ToString());
writer.AddDocument(doc);
count++;
}
reader = DirectoryReader.Open(writer, false);
Terms terms = MultiFields.GetTerms(reader, "body");
if (terms is null)
{
throw new ArgumentException("need at least one suggestion");
}
// Move all ngrams into an FST:
TermsEnum termsEnum = terms.GetEnumerator(null);
Outputs<Int64> outputs = PositiveInt32Outputs.Singleton;
Builder<Int64> builder = new Builder<Int64>(FST.INPUT_TYPE.BYTE1, outputs);
Int32sRef scratchInts = new Int32sRef();
while (termsEnum.MoveNext())
{
BytesRef term = termsEnum.Term;
int ngramCount = CountGrams(term);
if (ngramCount > grams)
{
throw new ArgumentException("tokens must not contain separator byte; got token=" + term + " but gramCount=" + ngramCount + ", which is greater than expected max ngram size=" + grams);
}
if (ngramCount == 1)
{
totTokens += termsEnum.TotalTermFreq;
}
builder.Add(Lucene.Net.Util.Fst.Util.ToInt32sRef(term, scratchInts), EncodeWeight(termsEnum.TotalTermFreq));
}
fst = builder.Finish();
if (fst is null)
{
throw new ArgumentException("need at least one suggestion");
}
//System.out.println("FST: " + fst.getNodeCount() + " nodes");
/*
PrintWriter pw = new PrintWriter("/x/tmp/out.dot");
Util.toDot(fst, pw, true, true);
pw.close();
*/
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(writer, reader);
}
else
{
IOUtils.DisposeWhileHandlingException(writer, reader);
}
}
}
finally
{
try
{
IOUtils.Dispose(dir);
}
finally
{
// LUCENENET specific - since we are removing the entire directory anyway,
// it doesn't make sense to first do a loop in order remove the files.
// Let the System.IO.Directory.Delete() method handle that.
// We also need to dispose the Directory instance first before deleting from disk.
try
{
System.IO.Directory.Delete(tempIndexPath.FullName, true);
}
catch (Exception e)
{
throw IllegalStateException.Create("failed to remove " + tempIndexPath, e);
}
}
}
}
public override bool Store(DataOutput output)
{
CodecUtil.WriteHeader(output, CODEC_NAME, VERSION_CURRENT);
output.WriteVInt64(count);
output.WriteByte(separator);
output.WriteVInt32(grams);
output.WriteVInt64(totTokens);
fst.Save(output);
return true;
}
public override bool Load(DataInput input)
{
CodecUtil.CheckHeader(input, CODEC_NAME, VERSION_START, VERSION_START);
count = input.ReadVInt64();
var separatorOrig = (sbyte)input.ReadByte();
if (separatorOrig != separator)
{
throw IllegalStateException.Create("separator=" + separator + " is incorrect: original model was built with separator=" + separatorOrig);
}
int gramsOrig = input.ReadVInt32();
if (gramsOrig != grams)
{
throw IllegalStateException.Create("grams=" + grams + " is incorrect: original model was built with grams=" + gramsOrig);
}
totTokens = input.ReadVInt64();
fst = new FST<Int64>(input, PositiveInt32Outputs.Singleton);
return true;
}
public override IList<LookupResult> DoLookup(string key,
bool onlyMorePopular,
int num,
CancellationToken cancellationToken = default) // ignored
{
return DoLookup(key, null, onlyMorePopular, num, cancellationToken);
}
/// <summary>
/// Lookup, without any context. </summary>
public virtual IList<LookupResult> DoLookup(string key, int num, CancellationToken cancellationToken = default)
{
return DoLookup(key, null, true, num, cancellationToken);
}
public override IList<LookupResult> DoLookup(string key,
IEnumerable<BytesRef> contexts, /* ignored */
bool onlyMorePopular,
int num,
CancellationToken cancellationToken = default)
{
try
{
return DoLookup(key, contexts, num, cancellationToken);
}
catch (Exception ioe) when (ioe.IsIOException())
{
// bogus:
throw RuntimeException.Create(ioe);
}
}
public override long Count => count;
private int CountGrams(BytesRef token)
{
int count = 1;
for (int i = 0; i < token.Length; i++)
{
if (token.Bytes[token.Offset + i] == separator)
{
count++;
}
}
return count;
}
/// <summary>
/// Retrieve suggestions.
/// </summary>
public virtual IList<LookupResult> DoLookup(string key,
IEnumerable<BytesRef> contexts,
int num,
CancellationToken cancellationToken = default)
{
// LUCENENET: Added guard clause for null
if (key is null)
throw new ArgumentNullException(nameof(key));
if (contexts != null)
{
throw new ArgumentException("this suggester doesn't support contexts");
}
TokenStream ts = queryAnalyzer.GetTokenStream("", key);
try
{
ITermToBytesRefAttribute termBytesAtt = ts.AddAttribute<ITermToBytesRefAttribute>();
IOffsetAttribute offsetAtt = ts.AddAttribute<IOffsetAttribute>();
IPositionLengthAttribute posLenAtt = ts.AddAttribute<IPositionLengthAttribute>();
IPositionIncrementAttribute posIncAtt = ts.AddAttribute<IPositionIncrementAttribute>();
ts.Reset();
var lastTokens = new BytesRef[grams];
//System.out.println("lookup: key='" + key + "'");
// Run full analysis, but save only the
// last 1gram, last 2gram, etc.:
BytesRef tokenBytes = termBytesAtt.BytesRef;
int maxEndOffset = -1;
bool sawRealToken = false;
while (ts.IncrementToken())
{
termBytesAtt.FillBytesRef();
sawRealToken |= tokenBytes.Length > 0;
// TODO: this is somewhat iffy; today, ShingleFilter
// sets posLen to the gram count; maybe we should make
// a separate dedicated att for this?
int gramCount = posLenAtt.PositionLength;
if (Debugging.AssertsEnabled) Debugging.Assert(gramCount <= grams);
// Safety: make sure the recalculated count "agrees":
if (CountGrams(tokenBytes) != gramCount)
{
throw new ArgumentException("tokens must not contain separator byte; got token=" + tokenBytes + " but gramCount=" + gramCount + " does not match recalculated count=" + CountGrams(tokenBytes));
}
maxEndOffset = Math.Max(maxEndOffset, offsetAtt.EndOffset);
lastTokens[gramCount - 1] = BytesRef.DeepCopyOf(tokenBytes);
}
ts.End();
if (!sawRealToken)
{
throw new ArgumentException("no tokens produced by analyzer, or the only tokens were empty strings");
}
// Carefully fill last tokens with _ tokens;
// ShingleFilter apparently won't emit "only hole"
// tokens:
int endPosInc = posIncAtt.PositionIncrement;
// Note this will also be true if input is the empty
// string (in which case we saw no tokens and
// maxEndOffset is still -1), which in fact works out OK
// because we fill the unigram with an empty BytesRef
// below:
bool lastTokenEnded = offsetAtt.EndOffset > maxEndOffset || endPosInc > 0;
//System.out.println("maxEndOffset=" + maxEndOffset + " vs " + offsetAtt.EndOffset);
if (lastTokenEnded)
{
//System.out.println(" lastTokenEnded");
// If user hit space after the last token, then
// "upgrade" all tokens. This way "foo " will suggest
// all bigrams starting w/ foo, and not any unigrams
// starting with "foo":
for (int i = grams - 1; i > 0; i--)
{
BytesRef token = lastTokens[i - 1];
if (token is null)
{
continue;
}
token.Grow(token.Length + 1);
token.Bytes[token.Length] = separator;
token.Length++;
lastTokens[i] = token;
}
lastTokens[0] = new BytesRef();
}
var arc = new FST.Arc<Int64>();
var bytesReader = fst.GetBytesReader();
// Try highest order models first, and if they return
// results, return that; else, fallback:
double backoff = 1.0;
JCG.List<LookupResult> results = new JCG.List<LookupResult>(num);
// We only add a given suffix once, from the highest
// order model that saw it; for subsequent lower order
// models we skip it:
var seen = new JCG.HashSet<BytesRef>();
for (int gram = grams - 1; gram >= 0; gram--)
{
BytesRef token = lastTokens[gram];
// Don't make unigram predictions from empty string:
if (token is null || (token.Length == 0 && key.Length > 0))
{
// Input didn't have enough tokens:
//System.out.println(" gram=" + gram + ": skip: not enough input");
continue;
}
if (endPosInc > 0 && gram <= endPosInc)
{
// Skip hole-only predictions; in theory we
// shouldn't have to do this, but we'd need to fix
// ShingleFilter to produce only-hole tokens:
//System.out.println(" break: only holes now");
break;
}
//System.out.println("try " + (gram+1) + " gram token=" + token.utf8ToString());
// TODO: we could add fuzziness here
// match the prefix portion exactly
//Pair<Long,BytesRef> prefixOutput = null;
Int64 prefixOutput = null;
try
{
prefixOutput = LookupPrefix(fst, bytesReader, token, arc);
}
catch (Exception bogus) when (bogus.IsIOException())
{
throw RuntimeException.Create(bogus);
}
//System.out.println(" prefixOutput=" + prefixOutput);
if (prefixOutput is null)
{
// This model never saw this prefix, e.g. the
// trigram model never saw context "purple mushroom"
backoff *= ALPHA;
continue;
}
// TODO: we could do this division at build time, and
// bake it into the FST?
// Denominator for computing scores from current
// model's predictions:
long contextCount = totTokens;
BytesRef lastTokenFragment = null;
for (int i = token.Length - 1; i >= 0; i--)
{
if (token.Bytes[token.Offset + i] == separator)
{
BytesRef context = new BytesRef(token.Bytes, token.Offset, i);
long? output = Lucene.Net.Util.Fst.Util.Get(fst, Lucene.Net.Util.Fst.Util.ToInt32sRef(context, new Int32sRef()));
if (Debugging.AssertsEnabled) Debugging.Assert(output != null);
contextCount = DecodeWeight(output);
lastTokenFragment = new BytesRef(token.Bytes, token.Offset + i + 1, token.Length - i - 1);
break;
}
}
BytesRef finalLastToken;
if (lastTokenFragment is null)
{
finalLastToken = BytesRef.DeepCopyOf(token);
}
else
{
finalLastToken = BytesRef.DeepCopyOf(lastTokenFragment);
}
if (Debugging.AssertsEnabled) Debugging.Assert(finalLastToken.Offset == 0);
CharsRef spare = new CharsRef();
// complete top-N
Util.Fst.Util.TopResults<Int64> completions = null;
try
{
// Because we store multiple models in one FST
// (1gram, 2gram, 3gram), we must restrict the
// search so that it only considers the current
// model. For highest order model, this is not
// necessary since all completions in the FST
// must be from this model, but for lower order
// models we have to filter out the higher order
// ones:
// Must do num+seen.size() for queue depth because we may
// reject up to seen.size() paths in acceptResult():
Util.Fst.Util.TopNSearcher<Int64> searcher = new TopNSearcherAnonymousClass(this, fst, num, num + seen.Count, weightComparer, seen, finalLastToken);
// since this search is initialized with a single start node
// it is okay to start with an empty input path here
searcher.AddStartPaths(arc, prefixOutput, true, new Int32sRef());
completions = searcher.Search();
if (Debugging.AssertsEnabled) Debugging.Assert(completions.IsComplete);
}
catch (Exception bogus) when (bogus.IsIOException())
{
throw RuntimeException.Create(bogus);
}
int prefixLength = token.Length;
BytesRef suffix = new BytesRef(8);
//System.out.println(" " + completions.length + " completions");
foreach (Util.Fst.Util.Result<Int64> completion in completions)
{
token.Length = prefixLength;
// append suffix
Util.Fst.Util.ToBytesRef(completion.Input, suffix);
token.Append(suffix);
//System.out.println(" completion " + token.utf8ToString());
// Skip this path if a higher-order model already
// saw/predicted its last token:
BytesRef lastToken = token;
for (int i = token.Length - 1; i >= 0; i--)
{
if (token.Bytes[token.Offset + i] == separator)
{
if (Debugging.AssertsEnabled) Debugging.Assert(token.Length - i - 1 > 0);
lastToken = new BytesRef(token.Bytes, token.Offset + i + 1, token.Length - i - 1);
break;
}
}
if (seen.Contains(lastToken))
{
//System.out.println(" skip dup " + lastToken.utf8ToString());
goto nextCompletionContinue;
}
seen.Add(BytesRef.DeepCopyOf(lastToken));
spare.Grow(token.Length);
UnicodeUtil.UTF8toUTF16(token, spare);
LookupResult result = new LookupResult(spare.ToString(),
// LUCENENET NOTE: We need to calculate this as decimal because when using double it can sometimes
// return numbers that are greater than long.MaxValue, which results in a negative long number.
(long)(long.MaxValue * (decimal)backoff * ((decimal)DecodeWeight(completion.Output)) / contextCount));
results.Add(result);
if (Debugging.AssertsEnabled) Debugging.Assert(results.Count == seen.Count);
//System.out.println(" add result=" + result);
nextCompletionContinue: {/* LUCENENET: intentionally blank */}
}
backoff *= ALPHA;
}
results.Sort(Comparer<Lookup.LookupResult>.Create((a, b) =>
{
if (a.Value > b.Value)
{
return -1;
}
else if (a.Value < b.Value)
{
return 1;
}
else
{
// Tie break by UTF16 sort order:
return a.Key.CompareToOrdinal(b.Key);
}
}));
if (results.Count > num)
{
results.RemoveRange(num, results.Count - num); // LUCENENET: Converted end index to length
}
return results;
}
finally
{
IOUtils.CloseWhileHandlingException(ts);
}
}
private sealed class TopNSearcherAnonymousClass : Util.Fst.Util.TopNSearcher<Int64>
{
private readonly FreeTextSuggester outerInstance;
private readonly ISet<BytesRef> seen;
private readonly BytesRef finalLastToken;
public TopNSearcherAnonymousClass(
FreeTextSuggester outerInstance,
FST<Int64> fst,
int num,
int size,
IComparer<Int64> weightComparer,
ISet<BytesRef> seen,
BytesRef finalLastToken)
: base(fst, num, size, weightComparer)
{
this.outerInstance = outerInstance;
this.seen = seen;
this.finalLastToken = finalLastToken;
scratchBytes = new BytesRef();
}
private readonly BytesRef scratchBytes;
protected override void AddIfCompetitive(Util.Fst.Util.FSTPath<Int64> path)
{
if (path.Arc.Label != outerInstance.separator)
{
//System.out.println(" keep path: " + Util.toBytesRef(path.input, new BytesRef()).utf8ToString() + "; " + path + "; arc=" + path.arc);
base.AddIfCompetitive(path);
}
else
{
//System.out.println(" prevent path: " + Util.toBytesRef(path.input, new BytesRef()).utf8ToString() + "; " + path + "; arc=" + path.arc);
}
}
protected override bool AcceptResult(Int32sRef input, Int64 output)
{
Util.Fst.Util.ToBytesRef(input, scratchBytes);
finalLastToken.Grow(finalLastToken.Length + scratchBytes.Length);
int lenSav = finalLastToken.Length;
finalLastToken.Append(scratchBytes);
//System.out.println(" accept? input='" + scratchBytes.utf8ToString() + "'; lastToken='" + finalLastToken.utf8ToString() + "'; return " + (seen.contains(finalLastToken) == false));
bool ret = seen.Contains(finalLastToken) == false;
finalLastToken.Length = lenSav;
return ret;
}
}
/// <summary>
/// weight -> cost </summary>
private static long EncodeWeight(long ngramCount) // LUCENENET: CA1822: Mark members as static
{
return long.MaxValue - ngramCount;
}
/// <summary>
/// cost -> weight </summary>
//private long decodeWeight(Pair<Long,BytesRef> output) {
private static long DecodeWeight(long? output)
{
if (Debugging.AssertsEnabled) Debugging.Assert(output != null);
return (int)(long.MaxValue - output); // LUCENENET TODO: Perhaps a Java Lucene bug? Why cast to int when returning long?
}
// NOTE: copied from WFSTCompletionLookup & tweaked
private static Int64 LookupPrefix(FST<Int64> fst, FST.BytesReader bytesReader, BytesRef scratch, FST.Arc<Int64> arc) // LUCENENET: CA1822: Mark members as static
{
Int64 output = fst.Outputs.NoOutput;
fst.GetFirstArc(arc);
var bytes = scratch.Bytes;
var pos = scratch.Offset;
var end = pos + scratch.Length;
while (pos < end)
{
if (fst.FindTargetArc(bytes[pos++] & 0xff, arc, arc, bytesReader) is null)
{
return null;
}
else
{
output = fst.Outputs.Add(output, arc.Output);
}
}
return output;
}
internal static readonly IComparer<Int64> weightComparer = Comparer<Int64>.Default;
/// <summary>
/// Returns the weight associated with an input string,
/// or null if it does not exist.
/// </summary>
public virtual object Get(string key)
{
throw UnsupportedOperationException.Create();
}
}
}