-
Notifications
You must be signed in to change notification settings - Fork 623
/
JapaneseTokenizer.cs
1495 lines (1324 loc) · 61.1 KB
/
JapaneseTokenizer.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
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
using J2N;
using Lucene.Net.Analysis.Ja.Dict;
using Lucene.Net.Analysis.Ja.TokenAttributes;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using Lucene.Net.Util;
using Lucene.Net.Util.Fst;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using Console = Lucene.Net.Util.SystemConsole;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Analysis.Ja
{
/*
* 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.
*/
/// <summary>
/// Tokenizer for Japanese that uses morphological analysis.
/// </summary>
/// <remarks>
/// This tokenizer sets a number of additional attributes:
/// <list type="bullet">
/// <item><description><see cref="IBaseFormAttribute"/> containing base form for inflected adjectives and verbs.</description></item>
/// <item><description><see cref="IPartOfSpeechAttribute"/> containing part-of-speech.</description></item>
/// <item><description><see cref="IReadingAttribute"/> containing reading and pronunciation.</description></item>
/// <item><description><see cref="IInflectionAttribute"/> containing additional part-of-speech information for inflected forms.</description></item>
/// </list>
/// <para/>
/// This tokenizer uses a rolling Viterbi search to find the
/// least cost segmentation (path) of the incoming characters.
/// For tokens that appear to be compound (> length 2 for all
/// Kanji, or > length 7 for non-Kanji), we see if there is a
/// 2nd best segmentation of that token after applying
/// penalties to the long tokens. If so, and the Mode is
/// <see cref="JapaneseTokenizerMode.SEARCH"/>, we output the alternate segmentation
/// as well.
/// </remarks>
public sealed class JapaneseTokenizer : Tokenizer
{
// LUCENENET specific: de-nested Mode and renamed JapaneseTokenizerMode
/// <summary>
/// Default tokenization mode. Currently this is <see cref="JapaneseTokenizerMode.SEARCH"/>.
/// </summary>
public static readonly JapaneseTokenizerMode DEFAULT_MODE = JapaneseTokenizerMode.SEARCH;
// LUCENENET specific: de-nested Type and renamed JapaneseTokenizerType
#pragma warning disable CA1802 // Use literals where appropriate
private static readonly bool VERBOSE = false; // For debugging
#pragma warning restore CA1802 // Use literals where appropriate
private const int SEARCH_MODE_KANJI_LENGTH = 2;
private const int SEARCH_MODE_OTHER_LENGTH = 7; // Must be >= SEARCH_MODE_KANJI_LENGTH
private const int SEARCH_MODE_KANJI_PENALTY = 3000;
private const int SEARCH_MODE_OTHER_PENALTY = 1700;
// For safety:
private const int MAX_UNKNOWN_WORD_LENGTH = 1024;
private const int MAX_BACKTRACE_GAP = 1024;
private readonly IDictionary<JapaneseTokenizerType, IDictionary> dictionaryMap = new Dictionary<JapaneseTokenizerType, IDictionary>();
private readonly TokenInfoFST fst;
private readonly TokenInfoDictionary dictionary;
private readonly UnknownDictionary unkDictionary;
private readonly ConnectionCosts costs;
private readonly UserDictionary userDictionary;
private readonly CharacterDefinition characterDefinition;
private readonly FST.Arc<long?> arc = new FST.Arc<long?>();
private readonly FST.BytesReader fstReader;
private readonly Int32sRef wordIdRef = new Int32sRef();
private readonly FST.BytesReader userFSTReader;
private readonly TokenInfoFST userFST;
private readonly RollingCharBuffer buffer = new RollingCharBuffer();
private readonly WrappedPositionArray positions = new WrappedPositionArray();
private readonly bool discardPunctuation;
private readonly bool searchMode;
private readonly bool extendedMode;
private readonly bool outputCompounds;
// Index of the last character of unknown word:
private int unknownWordEndIndex = -1;
// True once we've hit the EOF from the input reader:
private bool end;
// Last absolute position we backtraced from:
private int lastBackTracePos;
// Position of last token we returned; we use this to
// figure out whether to set posIncr to 0 or 1:
private int lastTokenPos;
// Next absolute position to process:
private int pos;
// Already parsed, but not yet passed to caller, tokens:
private readonly JCG.List<Token> pending = new JCG.List<Token>();
private readonly ICharTermAttribute termAtt;
private readonly IOffsetAttribute offsetAtt;
private readonly IPositionIncrementAttribute posIncAtt;
private readonly IPositionLengthAttribute posLengthAtt;
private readonly IBaseFormAttribute basicFormAtt;
private readonly IPartOfSpeechAttribute posAtt;
private readonly IReadingAttribute readingAtt;
private readonly IInflectionAttribute inflectionAtt;
/// <summary>
/// Create a new JapaneseTokenizer.
/// <para/>
/// Uses the default AttributeFactory.
/// </summary>
/// <param name="input">TextReader containing text.</param>
/// <param name="userDictionary">Optional: if non-null, user dictionary.</param>
/// <param name="discardPunctuation"><c>true</c> if punctuation tokens should be dropped from the output.</param>
/// <param name="mode">Tokenization mode.</param>
public JapaneseTokenizer(TextReader input, UserDictionary userDictionary, bool discardPunctuation, JapaneseTokenizerMode mode)
: this(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY, input, userDictionary, discardPunctuation, mode)
{
}
/// <summary>
/// Create a new JapaneseTokenizer.
/// </summary>
/// <param name="factory">The AttributeFactory to use.</param>
/// <param name="input">TextReader containing text.</param>
/// <param name="userDictionary">Optional: if non-null, user dictionary.</param>
/// <param name="discardPunctuation"><c>true</c> if punctuation tokens should be dropped from the output.</param>
/// <param name="mode">Tokenization mode.</param>
public JapaneseTokenizer
(AttributeFactory factory, TextReader input, UserDictionary userDictionary, bool discardPunctuation, JapaneseTokenizerMode mode)
: base(factory, input)
{
this.termAtt = AddAttribute<ICharTermAttribute>();
this.offsetAtt = AddAttribute<IOffsetAttribute>();
this.posIncAtt = AddAttribute<IPositionIncrementAttribute>();
this.posLengthAtt = AddAttribute<IPositionLengthAttribute>();
this.basicFormAtt = AddAttribute<IBaseFormAttribute>();
this.posAtt = AddAttribute<IPartOfSpeechAttribute>();
this.readingAtt = AddAttribute<IReadingAttribute>();
this.inflectionAtt = AddAttribute<IInflectionAttribute>();
dictionary = TokenInfoDictionary.Instance;
fst = dictionary.FST;
unkDictionary = UnknownDictionary.Instance;
characterDefinition = unkDictionary.CharacterDefinition;
this.userDictionary = userDictionary;
costs = ConnectionCosts.Instance;
fstReader = fst.GetBytesReader();
if (userDictionary != null)
{
userFST = userDictionary.FST;
userFSTReader = userFST.GetBytesReader();
}
else
{
userFST = null;
userFSTReader = null;
}
this.discardPunctuation = discardPunctuation;
switch (mode)
{
case JapaneseTokenizerMode.SEARCH:
searchMode = true;
extendedMode = false;
outputCompounds = true;
break;
case JapaneseTokenizerMode.EXTENDED:
searchMode = true;
extendedMode = true;
outputCompounds = false;
break;
default:
searchMode = false;
extendedMode = false;
outputCompounds = false;
break;
}
buffer.Reset(this.m_input);
ResetState();
dictionaryMap[JapaneseTokenizerType.KNOWN] = dictionary;
dictionaryMap[JapaneseTokenizerType.UNKNOWN] = unkDictionary;
dictionaryMap[JapaneseTokenizerType.USER] = userDictionary;
}
private GraphvizFormatter dotOut;
// LUCENENET specific - added getter and made into property
// so we can set this during object initialization.
/// <summary>
/// Expert: set this to produce graphviz (dot) output of
/// the Viterbi lattice
/// </summary>
public GraphvizFormatter GraphvizFormatter
{
get => this.dotOut;
set => this.dotOut = value;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
buffer.Reset(m_input);
}
}
public override void Reset()
{
base.Reset();
buffer.Reset(m_input);
ResetState();
}
private void ResetState()
{
positions.Reset();
unknownWordEndIndex = -1;
pos = 0;
end = false;
lastBackTracePos = 0;
lastTokenPos = -1;
pending.Clear();
// Add BOS:
positions.Get(0).Add(0, 0, -1, -1, -1, JapaneseTokenizerType.KNOWN);
}
public override void End()
{
base.End();
// Set final offset
int finalOffset = CorrectOffset(pos);
offsetAtt.SetOffset(finalOffset, finalOffset);
}
// Returns the added cost that a 2nd best segmentation is
// allowed to have. Ie, if we see path with cost X,
// ending in a compound word, and this method returns
// threshold > 0, then we will also find the 2nd best
// segmentation and if its path score is within this
// threshold of X, we'll include it in the output:
private int ComputeSecondBestThreshold(int pos, int length)
{
// TODO: maybe we do something else here, instead of just
// using the penalty...? EG we can be more aggressive on
// when to also test for 2nd best path
return ComputePenalty(pos, length);
}
private int ComputePenalty(int pos, int length)
{
if (length > SEARCH_MODE_KANJI_LENGTH)
{
bool allKanji = true;
// check if node consists of only kanji
int endPos = pos + length;
for (int pos2 = pos; pos2 < endPos; pos2++)
{
if (!characterDefinition.IsKanji((char)buffer.Get(pos2)))
{
allKanji = false;
break;
}
}
if (allKanji)
{ // Process only Kanji keywords
return (length - SEARCH_MODE_KANJI_LENGTH) * SEARCH_MODE_KANJI_PENALTY;
}
else if (length > SEARCH_MODE_OTHER_LENGTH)
{
return (length - SEARCH_MODE_OTHER_LENGTH) * SEARCH_MODE_OTHER_PENALTY;
}
}
return 0;
}
// LUCENENET specific - de-nested Position class
private void Add(IDictionary dict, Position fromPosData, int endPos, int wordID, JapaneseTokenizerType type, bool addPenalty)
{
int wordCost = dict.GetWordCost(wordID);
int leftID = dict.GetLeftId(wordID);
int leastCost = int.MaxValue;
int leastIDX = -1;
if (Debugging.AssertsEnabled) Debugging.Assert(fromPosData.count > 0);
for (int idx = 0; idx < fromPosData.count; idx++)
{
// Cost is path cost so far, plus word cost (added at
// end of loop), plus bigram cost:
int cost = fromPosData.costs[idx] + costs.Get(fromPosData.lastRightID[idx], leftID);
if (VERBOSE)
{
Console.WriteLine(" fromIDX=" + idx + ": cost=" + cost + " (prevCost=" + fromPosData.costs[idx] + " wordCost=" + wordCost + " bgCost=" + costs.Get(fromPosData.lastRightID[idx], leftID) + " leftID=" + leftID);
}
if (cost < leastCost)
{
leastCost = cost;
leastIDX = idx;
if (VERBOSE)
{
Console.WriteLine(" **");
}
}
}
leastCost += wordCost;
if (VERBOSE)
{
Console.WriteLine(" + cost=" + leastCost + " wordID=" + wordID + " leftID=" + leftID + " leastIDX=" + leastIDX + " toPos=" + endPos + " toPos.idx=" + positions.Get(endPos).count);
}
if ((addPenalty || (!outputCompounds && searchMode)) && type != JapaneseTokenizerType.USER)
{
int penalty = ComputePenalty(fromPosData.pos, endPos - fromPosData.pos);
if (VERBOSE)
{
if (penalty > 0)
{
Console.WriteLine(" + penalty=" + penalty + " cost=" + (leastCost + penalty));
}
}
leastCost += penalty;
}
//positions.get(endPos).add(leastCost, dict.getRightId(wordID), fromPosData.pos, leastIDX, wordID, type);
if (Debugging.AssertsEnabled) Debugging.Assert(leftID == dict.GetRightId(wordID));
positions.Get(endPos).Add(leastCost, leftID, fromPosData.pos, leastIDX, wordID, type);
}
public override bool IncrementToken()
{
// parse() is able to return w/o producing any new
// tokens, when the tokens it had produced were entirely
// punctuation. So we loop here until we get a real
// token or we end:
while (pending.Count == 0)
{
if (end)
{
return false;
}
// Push Viterbi forward some more:
Parse();
}
Token token = pending[pending.Count - 1]; // LUCENENET: The above loop ensures we don't get here unless we have at least 1 item
if (token != null)
{
pending.Remove(token);
}
int position = token.Position;
int length = token.Length;
ClearAttributes();
if (Debugging.AssertsEnabled) Debugging.Assert(length > 0);
//System.out.println("off=" + token.getOffset() + " len=" + length + " vs " + token.getSurfaceForm().length);
termAtt.CopyBuffer(token.SurfaceForm, token.Offset, length);
offsetAtt.SetOffset(CorrectOffset(position), CorrectOffset(position + length));
basicFormAtt.SetToken(token);
posAtt.SetToken(token);
readingAtt.SetToken(token);
inflectionAtt.SetToken(token);
if (token.Position == lastTokenPos)
{
posIncAtt.PositionIncrement = 0;
posLengthAtt.PositionLength = token.PositionLength;
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(token.Position > lastTokenPos);
posIncAtt.PositionIncrement = 1;
posLengthAtt.PositionLength = 1;
}
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": incToken: return token=" + token);
}
lastTokenPos = token.Position;
return true;
}
/// <summary>
/// Incrementally parse some more characters. This runs
/// the viterbi search forwards "enough" so that we
/// generate some more tokens. How much forward depends on
/// the chars coming in, since some chars could cause
/// longer-lasting ambiguity in the parsing. Once the
/// ambiguity is resolved, then we back trace, produce
/// the pending tokens, and return.
/// </summary>
private void Parse()
{
if (VERBOSE)
{
Console.WriteLine("\nPARSE");
}
// Advances over each position (character):
while (true)
{
if (buffer.Get(pos) == -1)
{
// End
break;
}
Position posData = positions.Get(pos);
bool isFrontier = positions.GetNextPos() == pos + 1;
if (posData.count == 0)
{
// No arcs arrive here; move to next position:
if (VERBOSE)
{
Console.WriteLine(" no arcs in; skip pos=" + pos);
}
pos++;
continue;
}
if (pos > lastBackTracePos && posData.count == 1 && isFrontier)
{
// if (pos > lastBackTracePos && posData.count == 1 && isFrontier) {
// We are at a "frontier", and only one node is
// alive, so whatever the eventual best path is must
// come through this node. So we can safely commit
// to the prefix of the best path at this point:
Backtrace(posData, 0);
// Re-base cost so we don't risk int overflow:
posData.costs[0] = 0;
if (pending.Count != 0)
{
return;
}
else
{
// This means the backtrace only produced
// punctuation tokens, so we must keep parsing.
}
}
if (pos - lastBackTracePos >= MAX_BACKTRACE_GAP)
{
// Safety: if we've buffered too much, force a
// backtrace now. We find the least-cost partial
// path, across all paths, backtrace from it, and
// then prune all others. Note that this, in
// general, can produce the wrong result, if the
// total best path did not in fact back trace
// through this partial best path. But it's the
// best we can do... (short of not having a
// safety!).
// First pass: find least cost partial path so far,
// including ending at future positions:
int leastIDX = -1;
int leastCost = int.MaxValue;
Position leastPosData = null;
for (int pos2 = pos; pos2 < positions.GetNextPos(); pos2++)
{
Position posData2 = positions.Get(pos2);
for (int idx = 0; idx < posData2.count; idx++)
{
//System.out.println(" idx=" + idx + " cost=" + cost);
int cost = posData2.costs[idx];
if (cost < leastCost)
{
leastCost = cost;
leastIDX = idx;
leastPosData = posData2;
}
}
}
// We will always have at least one live path:
if (Debugging.AssertsEnabled) Debugging.Assert(leastIDX != -1);
// Second pass: prune all but the best path:
for (int pos2 = pos; pos2 < positions.GetNextPos(); pos2++)
{
Position posData2 = positions.Get(pos2);
if (posData2 != leastPosData)
{
posData2.Reset();
}
else
{
if (leastIDX != 0)
{
posData2.costs[0] = posData2.costs[leastIDX];
posData2.lastRightID[0] = posData2.lastRightID[leastIDX];
posData2.backPos[0] = posData2.backPos[leastIDX];
posData2.backIndex[0] = posData2.backIndex[leastIDX];
posData2.backID[0] = posData2.backID[leastIDX];
posData2.backType[0] = posData2.backType[leastIDX];
}
posData2.count = 1;
}
}
Backtrace(leastPosData, 0);
// Re-base cost so we don't risk int overflow:
Arrays.Fill(leastPosData.costs, 0, leastPosData.count, 0);
if (pos != leastPosData.pos)
{
// We jumped into a future position:
if (Debugging.AssertsEnabled) Debugging.Assert(pos < leastPosData.pos);
pos = leastPosData.pos;
}
if (pending.Count != 0)
{
return;
}
else
{
// This means the backtrace only produced
// punctuation tokens, so we must keep parsing.
continue;
}
}
if (VERBOSE)
{
Console.WriteLine("\n extend @ pos=" + pos + " char=" + (char)buffer.Get(pos));
}
if (VERBOSE)
{
Console.WriteLine(" " + posData.count + " arcs in");
}
bool anyMatches = false;
// First try user dict:
if (userFST != null)
{
userFST.GetFirstArc(arc);
int output = 0;
for (int posAhead = posData.pos; ; posAhead++)
{
int ch = buffer.Get(posAhead);
if (ch == -1)
{
break;
}
if (userFST.FindTargetArc(ch, arc, arc, posAhead == posData.pos, userFSTReader) == null)
{
break;
}
output += (int)arc.Output;
if (arc.IsFinal)
{
if (VERBOSE)
{
Console.WriteLine(" USER word " + new string(buffer.Get(pos, posAhead - pos + 1)) + " toPos=" + (posAhead + 1));
}
Add(userDictionary, posData, posAhead + 1, output + (int)arc.NextFinalOutput, JapaneseTokenizerType.USER, false);
anyMatches = true;
}
}
}
// TODO: we can be more aggressive about user
// matches? if we are "under" a user match then don't
// extend KNOWN/UNKNOWN paths?
if (!anyMatches)
{
// Next, try known dictionary matches
fst.GetFirstArc(arc);
int output = 0;
for (int posAhead = posData.pos; ; posAhead++)
{
int ch = buffer.Get(posAhead);
if (ch == -1)
{
break;
}
//System.out.println(" match " + (char) ch + " posAhead=" + posAhead);
if (fst.FindTargetArc(ch, arc, arc, posAhead == posData.pos, fstReader) == null)
{
break;
}
output += (int)arc.Output;
// Optimization: for known words that are too-long
// (compound), we should pre-compute the 2nd
// best segmentation and store it in the
// dictionary instead of recomputing it each time a
// match is found.
if (arc.IsFinal)
{
dictionary.LookupWordIds(output + (int)arc.NextFinalOutput, wordIdRef);
if (VERBOSE)
{
Console.WriteLine(" KNOWN word " + new string(buffer.Get(pos, posAhead - pos + 1)) + " toPos=" + (posAhead + 1) + " " + wordIdRef.Length + " wordIDs");
}
for (int ofs = 0; ofs < wordIdRef.Length; ofs++)
{
Add(dictionary, posData, posAhead + 1, wordIdRef.Int32s[wordIdRef.Offset + ofs], JapaneseTokenizerType.KNOWN, false);
anyMatches = true;
}
}
}
}
// In the case of normal mode, it doesn't process unknown word greedily.
if (!searchMode && unknownWordEndIndex > posData.pos)
{
pos++;
continue;
}
char firstCharacter = (char)buffer.Get(pos);
if (!anyMatches || characterDefinition.IsInvoke(firstCharacter))
{
// Find unknown match:
int characterId = characterDefinition.GetCharacterClass(firstCharacter);
bool isPunct = IsPunctuation(firstCharacter);
// NOTE: copied from UnknownDictionary.lookup:
int unknownWordLength;
if (!characterDefinition.IsGroup(firstCharacter))
{
unknownWordLength = 1;
}
else
{
// Extract unknown word. Characters with the same character class are considered to be part of unknown word
unknownWordLength = 1;
for (int posAhead = pos + 1; unknownWordLength < MAX_UNKNOWN_WORD_LENGTH; posAhead++)
{
int ch = buffer.Get(posAhead);
if (ch == -1)
{
break;
}
if (characterId == characterDefinition.GetCharacterClass((char)ch) &&
IsPunctuation((char)ch) == isPunct)
{
unknownWordLength++;
}
else
{
break;
}
}
}
unkDictionary.LookupWordIds(characterId, wordIdRef); // characters in input text are supposed to be the same
if (VERBOSE)
{
Console.WriteLine(" UNKNOWN word len=" + unknownWordLength + " " + wordIdRef.Length + " wordIDs");
}
for (int ofs = 0; ofs < wordIdRef.Length; ofs++)
{
Add(unkDictionary, posData, posData.pos + unknownWordLength, wordIdRef.Int32s[wordIdRef.Offset + ofs], JapaneseTokenizerType.UNKNOWN, false);
}
unknownWordEndIndex = posData.pos + unknownWordLength;
}
pos++;
}
end = true;
if (pos > 0)
{
Position endPosData = positions.Get(pos);
int leastCost = int.MaxValue;
int leastIDX = -1;
if (VERBOSE)
{
Console.WriteLine(" end: " + endPosData.count + " nodes");
}
for (int idx = 0; idx < endPosData.count; idx++)
{
// Add EOS cost:
int cost = endPosData.costs[idx] + costs.Get(endPosData.lastRightID[idx], 0);
//System.out.println(" idx=" + idx + " cost=" + cost + " (pathCost=" + endPosData.costs[idx] + " bgCost=" + costs.get(endPosData.lastRightID[idx], 0) + ") backPos=" + endPosData.backPos[idx]);
if (cost < leastCost)
{
leastCost = cost;
leastIDX = idx;
}
}
Backtrace(endPosData, leastIDX);
}
else
{
// No characters in the input string; return no tokens!
}
}
// Eliminates arcs from the lattice that are compound
// tokens (have a penalty) or are not congruent with the
// compound token we've matched (ie, span across the
// startPos). This should be fairly efficient, because we
// just keep the already intersected structure of the
// graph, eg we don't have to consult the FSTs again:
private void PruneAndRescore(int startPos, int endPos, int bestStartIDX)
{
if (VERBOSE)
{
Console.WriteLine(" pruneAndRescore startPos=" + startPos + " endPos=" + endPos + " bestStartIDX=" + bestStartIDX);
}
// First pass: walk backwards, building up the forward
// arcs and pruning inadmissible arcs:
for (int pos = endPos; pos > startPos; pos--)
{
Position posData = positions.Get(pos);
if (VERBOSE)
{
Console.WriteLine(" back pos=" + pos);
}
for (int arcIDX = 0; arcIDX < posData.count; arcIDX++)
{
int backPos = posData.backPos[arcIDX];
if (backPos >= startPos)
{
// Keep this arc:
//System.out.println(" keep backPos=" + backPos);
positions.Get(backPos).AddForward(pos,
arcIDX,
posData.backID[arcIDX],
posData.backType[arcIDX]);
}
else
{
if (VERBOSE)
{
Console.WriteLine(" prune");
}
}
}
if (pos != startPos)
{
posData.count = 0;
}
}
// Second pass: walk forward, re-scoring:
for (int pos = startPos; pos < endPos; pos++)
{
Position posData = positions.Get(pos);
if (VERBOSE)
{
Console.WriteLine(" forward pos=" + pos + " count=" + posData.forwardCount);
}
if (posData.count == 0)
{
// No arcs arrive here...
if (VERBOSE)
{
Console.WriteLine(" skip");
}
posData.forwardCount = 0;
continue;
}
if (pos == startPos)
{
// On the initial position, only consider the best
// path so we "force congruence": the
// sub-segmentation is "in context" of what the best
// path (compound token) had matched:
int rightID;
if (startPos == 0)
{
rightID = 0;
}
else
{
rightID = GetDict(posData.backType[bestStartIDX]).GetRightId(posData.backID[bestStartIDX]);
}
int pathCost = posData.costs[bestStartIDX];
for (int forwardArcIDX = 0; forwardArcIDX < posData.forwardCount; forwardArcIDX++)
{
JapaneseTokenizerType forwardType = posData.forwardType[forwardArcIDX];
IDictionary dict2 = GetDict(forwardType);
int wordID = posData.forwardID[forwardArcIDX];
int toPos = posData.forwardPos[forwardArcIDX];
int newCost = pathCost + dict2.GetWordCost(wordID) +
costs.Get(rightID, dict2.GetLeftId(wordID)) +
ComputePenalty(pos, toPos - pos);
if (VERBOSE)
{
Console.WriteLine(" + " + forwardType + " word " + new string(buffer.Get(pos, toPos - pos)) + " toPos=" + toPos + " cost=" + newCost + " penalty=" + ComputePenalty(pos, toPos - pos) + " toPos.idx=" + positions.Get(toPos).count);
}
positions.Get(toPos).Add(newCost,
dict2.GetRightId(wordID),
pos,
bestStartIDX,
wordID,
forwardType);
}
}
else
{
// On non-initial positions, we maximize score
// across all arriving lastRightIDs:
for (int forwardArcIDX = 0; forwardArcIDX < posData.forwardCount; forwardArcIDX++)
{
JapaneseTokenizerType forwardType = posData.forwardType[forwardArcIDX];
int toPos = posData.forwardPos[forwardArcIDX];
if (VERBOSE)
{
Console.WriteLine(" + " + forwardType + " word " + new string(buffer.Get(pos, toPos - pos)) + " toPos=" + toPos);
}
Add(GetDict(forwardType),
posData,
toPos,
posData.forwardID[forwardArcIDX],
forwardType,
true);
}
}
posData.forwardCount = 0;
}
}
// Backtrace from the provided position, back to the last
// time we back-traced, accumulating the resulting tokens to
// the pending list. The pending list is then in-reverse
// (last token should be returned first).
private void Backtrace(Position endPosData, int fromIDX)
{
int endPos = endPosData.pos;
if (VERBOSE)
{
Console.WriteLine("\n backtrace: endPos=" + endPos + " pos=" + this.pos + "; " + (this.pos - lastBackTracePos) + " characters; last=" + lastBackTracePos + " cost=" + endPosData.costs[fromIDX]);
}
char[] fragment = buffer.Get(lastBackTracePos, endPos - lastBackTracePos);
if (dotOut != null)
{
dotOut.OnBacktrace(this, positions, lastBackTracePos, endPosData, fromIDX, fragment, end);
}
int pos = endPos;
int bestIDX = fromIDX;
Token altToken = null;
// We trace backwards, so this will be the leftWordID of
// the token after the one we are now on:
int lastLeftWordID = -1;
int backCount = 0;
// TODO: sort of silly to make Token instances here; the
// back trace has all info needed to generate the
// token. So, we could just directly set the attrs,
// from the backtrace, in incrementToken w/o ever
// creating Token; we'd have to defer calling freeBefore
// until after the backtrace was fully "consumed" by
// incrementToken.
while (pos > lastBackTracePos)
{
//System.out.println("BT: back pos=" + pos + " bestIDX=" + bestIDX);
Position posData = positions.Get(pos);
if (Debugging.AssertsEnabled) Debugging.Assert(bestIDX < posData.count);
int backPos = posData.backPos[bestIDX];
if (Debugging.AssertsEnabled) Debugging.Assert(backPos >= lastBackTracePos,"backPos={0} vs lastBackTracePos={1}", backPos, lastBackTracePos);
int length = pos - backPos;
JapaneseTokenizerType backType = posData.backType[bestIDX];
int backID = posData.backID[bestIDX];
int nextBestIDX = posData.backIndex[bestIDX];
if (outputCompounds && searchMode && altToken == null && backType != JapaneseTokenizerType.USER)
{
// In searchMode, if best path had picked a too-long
// token, we use the "penalty" to compute the allowed
// max cost of an alternate back-trace. If we find an
// alternate back trace with cost below that
// threshold, we pursue it instead (but also output
// the long token).
//System.out.println(" 2nd best backPos=" + backPos + " pos=" + pos);
int penalty = ComputeSecondBestThreshold(backPos, pos - backPos);
if (penalty > 0)
{
if (VERBOSE)
{
Console.WriteLine(" compound=" + new string(buffer.Get(backPos, pos - backPos)) + " backPos=" + backPos + " pos=" + pos + " penalty=" + penalty + " cost=" + posData.costs[bestIDX] + " bestIDX=" + bestIDX + " lastLeftID=" + lastLeftWordID);
}
// Use the penalty to set maxCost on the 2nd best
// segmentation:
int maxCost = posData.costs[bestIDX] + penalty;
if (lastLeftWordID != -1)
{
maxCost += costs.Get(GetDict(backType).GetRightId(backID), lastLeftWordID);
}
// Now, prune all too-long tokens from the graph:
PruneAndRescore(backPos, pos,
posData.backIndex[bestIDX]);
// Finally, find 2nd best back-trace and resume
// backtrace there:
int leastCost = int.MaxValue;
int leastIDX = -1;
for (int idx = 0; idx < posData.count; idx++)
{
int cost = posData.costs[idx];
//System.out.println(" idx=" + idx + " prevCost=" + cost);
if (lastLeftWordID != -1)
{
cost += costs.Get(GetDict(posData.backType[idx]).GetRightId(posData.backID[idx]),
lastLeftWordID);
//System.out.println(" += bgCost=" + costs.get(getDict(posData.backType[idx]).getRightId(posData.backID[idx]),
//lastLeftWordID) + " -> " + cost);
}
//System.out.println("penalty " + posData.backPos[idx] + " to " + pos);
//cost += computePenalty(posData.backPos[idx], pos - posData.backPos[idx]);
if (cost < leastCost)
{
//System.out.println(" ** ");
leastCost = cost;
leastIDX = idx;
}
}
//System.out.println(" leastIDX=" + leastIDX);
if (VERBOSE)
{
Console.WriteLine(" afterPrune: " + posData.count + " arcs arriving; leastCost=" + leastCost + " vs threshold=" + maxCost + " lastLeftWordID=" + lastLeftWordID);
}
if (leastIDX != -1 && leastCost <= maxCost && posData.backPos[leastIDX] != backPos)
{
// We should have pruned the altToken from the graph:
if (Debugging.AssertsEnabled) Debugging.Assert(posData.backPos[leastIDX] != backPos);
// Save the current compound token, to output when
// this alternate path joins back:
altToken = new Token(backID,
fragment,