forked from manticoresoftware/manticoresearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphinxaot.cpp
2208 lines (1855 loc) · 58.8 KB
/
sphinxaot.cpp
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
//
// Copyright (c) 2017-2023, Manticore Software LTD (https://manticoresearch.com)
// Copyright (c) 2011-2016, Andrew Aksyonoff
// Copyright (c) 2011-2016, Sphinx Technologies Inc
// All rights reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License. You should have
// received a copy of the GPL license along with this program; if you
// did not, you can find it at http://www.gnu.org/
//
// Based on AOT lemmatizer, http://aot.ru/
// Copyright (c) 2004-2014, Alexey Sokirko and others
//
#include "sphinxint.h"
#include "fileutils.h"
#include "sphinxstem.h"
#include "sphinxplugin.h"
#include "coroutine.h"
#include "tokenizer/token_filter.h"
#include "dict/word_forms.h"
//////////////////////////////////////////////////////////////////////////
// LEMMATIZER
//////////////////////////////////////////////////////////////////////////
const BYTE AOT_POS_UNKNOWN = 0xff;
const int AOT_MIN_PREDICTION_SUFFIX = 3;
const BYTE AOT_MORPH_ANNOT_CHAR = '+';
const int AOT_MAX_ALPHABET_SIZE = 54;
const DWORD AOT_NOFORM = 0xffffffffUL;
const DWORD AOT_ORIGFORM = 0xfffffffeUL;
static int g_iCacheSize = 262144; // in bytes, so 256K
#define AOT_MODEL_NO(_a) ((_a)>>18)
#define AOT_ITEM_NO(_a) (((_a)&0x3FFFF)>>9)
#define AOT_PREFIX_NO(_a) ((_a)&0x1FF)
/// morpohological form info
struct CMorphForm
{
BYTE m_FlexiaLen;
BYTE m_PrefixLen;
BYTE m_POS;
BYTE m_Dummy;
char m_Prefix[4];
char m_Flexia[24];
};
/// alphabet descriptor
struct AlphabetDesc_t
{
int m_iSize;
BYTE m_dCode2Alpha [ AOT_MAX_ALPHABET_SIZE ];
BYTE m_dCode2AlphaWA [ AOT_MAX_ALPHABET_SIZE ];
};
/// alphabet codec
class CABCEncoder : public ISphNoncopyable
{
public:
int m_AlphabetSize;
int m_Alphabet2Code[256];
int m_Alphabet2CodeWithoutAnnotator[256];
void InitAlphabet ( const AlphabetDesc_t & tDesc );
bool CheckABCWithoutAnnotator ( const BYTE * pWord ) const;
DWORD DecodeFromAlphabet ( const BYTE * sPath, int iPath ) const;
};
/// morphology automaton node, 1:31
/// 1 bit for "final or not" flag
/// 31 bits for index to relations (pointer to the first child)
struct CMorphAutomNode
{
DWORD m_Data;
DWORD GetChildrenStart() const { return m_Data&(0x80000000-1); }
bool IsFinal() const { return (m_Data&0x80000000) > 0; }
};
/// morphology automaton relation, 8:24
/// 8 bits for relational char (aka next char in current form)
/// 24 bites for index to nodes (pointer to the next level node)
struct CMorphAutomRelation
{
DWORD m_Data;
DWORD GetChildNo() const { return m_Data & 0xffffff; }
BYTE GetRelationalChar() const { return (BYTE)(m_Data>>24); }
};
/// morphology automaton
class CMorphAutomat : public CABCEncoder
{
protected:
CMorphAutomNode * m_pNodes;
int m_NodesCount;
CMorphAutomRelation * m_pRelations;
int m_RelationsCount;
int m_iCacheSize;
CSphTightVector<int> m_ChildrenCache;
void BuildChildrenCache ( int iCacheSize );
int FindStringAndPassAnnotChar ( const BYTE * pText ) const;
public:
CMorphAutomat ()
: m_pNodes ( NULL )
, m_NodesCount ( 0 )
, m_pRelations ( NULL )
, m_RelationsCount ( 0 )
, m_iCacheSize ( 0 )
{}
~CMorphAutomat ()
{
SafeDeleteArray ( m_pNodes );
SafeDeleteArray ( m_pRelations );
}
int GetChildrenCount ( int i ) const { return m_pNodes[i+1].GetChildrenStart() - m_pNodes[i].GetChildrenStart(); }
const CMorphAutomRelation * GetChildren ( int i ) const { return m_pRelations + m_pNodes[i].GetChildrenStart(); }
const CMorphAutomNode GetNode ( int i ) const { return m_pNodes[i]; }
public:
bool LoadPak ( CSphReader & rd, int iCacheSize );
void GetInnerMorphInfos ( const BYTE * pText, DWORD * Infos ) const;
int NextNode ( int NodeNo, BYTE Child ) const;
};
/// prediction data tuple
struct CPredictTuple
{
WORD m_ItemNo;
DWORD m_LemmaInfoNo;
BYTE m_PartOfSpeechNo;
};
/// flexia model is basically a vector of morphology forms
/// (there is other meta suff like per-model comments but that is now stripped)
typedef CSphVector<CMorphForm> CFlexiaModel;
/// lemmatizer
class CLemmatizer
{
protected:
static constexpr int MAX_PREFIX_LEN = 12;
static constexpr bool m_bMaximalPrediction = false;
bool m_bIsGerman;
BYTE m_UC[256];
CMorphAutomat m_FormAutomat;
CSphVector<WORD> m_LemmaFlexiaModel; ///< lemma id to flexia model id mapping
CSphVector<BYTE> m_NPSs;
int m_PrefixLen [ MAX_PREFIX_LEN ];
CSphVector<BYTE> m_PrefixBlob;
CMorphAutomat m_SuffixAutomat;
CSphVector<DWORD> m_ModelFreq;
bool IsPrefix ( const BYTE * sPrefix, int iLen ) const;
DWORD PredictPack ( const CPredictTuple & t ) const { return ( m_LemmaFlexiaModel [ t.m_LemmaInfoNo ]<<18 ) + ( t.m_ItemNo<<9 ); }
bool PredictFind ( const BYTE * pWord, int iLen, CSphVector<CPredictTuple> & res ) const;
void PredictFindRecursive ( int r, BYTE * sPath, int iPath, CSphVector<CPredictTuple> & Infos ) const;
void PredictByDataBase ( const BYTE * pWord, int iLen, DWORD * results, bool is_cap ) const;
public:
explicit CLemmatizer ( bool IsGerman = false )
: m_bIsGerman ( IsGerman )
, m_iLang ( 0 )
{}
CSphVector<CFlexiaModel> m_FlexiaModels; ///< flexia models
int m_iLang; ///< my language
bool LemmatizeWord ( BYTE * pWord, DWORD * results ) const;
bool LoadPak ( CSphReader & rd );
};
//////////////////////////////////////////////////////////////////////////
DWORD CABCEncoder::DecodeFromAlphabet ( const BYTE * sPath, int iPath ) const
{
DWORD c = 1;
DWORD Result = 0;
for ( const BYTE * sMax = sPath+iPath; sPath<sMax; sPath++ )
{
Result += m_Alphabet2CodeWithoutAnnotator[*sPath] * c;
c *= m_AlphabetSize - 1;
}
return Result;
}
bool CABCEncoder::CheckABCWithoutAnnotator ( const BYTE * pWord ) const
{
while ( *pWord )
if ( m_Alphabet2CodeWithoutAnnotator [ *pWord++ ]==-1 )
return false;
return true;
}
void CABCEncoder::InitAlphabet ( const AlphabetDesc_t & tDesc )
{
m_AlphabetSize = tDesc.m_iSize;
for ( int i=0; i<256; i++ )
{
m_Alphabet2Code[i] = -1;
m_Alphabet2CodeWithoutAnnotator[i] = -1;
}
for ( int i=0; i<m_AlphabetSize; i++ )
m_Alphabet2Code [ tDesc.m_dCode2Alpha[i] ] = i;
for ( int i=0; i<m_AlphabetSize-1; i++ )
m_Alphabet2CodeWithoutAnnotator [ tDesc.m_dCode2AlphaWA[i] ] = i;
}
//////////////////////////////////////////////////////////////////////////
void CMorphAutomat::BuildChildrenCache ( int iCacheSize )
{
iCacheSize /= AOT_MAX_ALPHABET_SIZE*4;
iCacheSize = Max ( iCacheSize, 0 );
m_iCacheSize = Min ( m_NodesCount, iCacheSize );
m_ChildrenCache.Resize ( m_iCacheSize*AOT_MAX_ALPHABET_SIZE );
m_ChildrenCache.Fill ( -1 );
for ( int NodeNo=0; NodeNo<m_iCacheSize; NodeNo++ )
{
const CMorphAutomRelation * pStart = m_pRelations + m_pNodes [ NodeNo ].GetChildrenStart();
const CMorphAutomRelation * pEnd = pStart + GetChildrenCount ( NodeNo );
for ( ; pStart!=pEnd; pStart++ )
{
const CMorphAutomRelation & p = *pStart;
m_ChildrenCache [ NodeNo*AOT_MAX_ALPHABET_SIZE + m_Alphabet2Code [ p.GetRelationalChar() ] ] = p.GetChildNo();
}
}
}
bool CMorphAutomat::LoadPak ( CSphReader & rd, int iCacheSize )
{
rd.Tag ( "automaton-nodes" );
m_NodesCount = rd.UnzipInt();
m_pNodes = new CMorphAutomNode [ m_NodesCount+1 ];
rd.GetBytes ( m_pNodes, m_NodesCount*sizeof(CMorphAutomNode) );
rd.Tag ( "automaton-relations" );
m_RelationsCount = rd.UnzipInt();
m_pRelations = new CMorphAutomRelation [ m_RelationsCount ];
rd.GetBytes ( m_pRelations, m_RelationsCount*sizeof(CMorphAutomRelation) );
if ( rd.GetErrorFlag() )
return false;
m_pNodes [ m_NodesCount ].m_Data = m_RelationsCount;
#if !USE_LITTLE_ENDIAN
for ( int i=0; i< m_NodesCount; ++i )
FlipEndianess ( &m_pNodes[i].m_Data );
for ( int i=0; i< m_RelationsCount; ++i )
FlipEndianess ( &m_pRelations[i].m_Data );
#endif
BuildChildrenCache ( iCacheSize );
return true;
}
int CMorphAutomat::NextNode ( int NodeNo, BYTE RelationChar ) const
{
if ( NodeNo<m_iCacheSize )
{
int z = m_Alphabet2Code [ RelationChar ];
if ( z==-1 )
return -1;
return m_ChildrenCache [ NodeNo*AOT_MAX_ALPHABET_SIZE + z ];
} else
{
const CMorphAutomRelation * pStart = m_pRelations + m_pNodes [ NodeNo ].GetChildrenStart();
const CMorphAutomRelation * pEnd = pStart + GetChildrenCount ( NodeNo );
for ( ; pStart!=pEnd; pStart++ )
{
const CMorphAutomRelation & p = *pStart;
if ( RelationChar==p.GetRelationalChar() )
return p.GetChildNo();
}
return -1;
}
}
int CMorphAutomat::FindStringAndPassAnnotChar ( const BYTE * pText ) const
{
int r = 0;
while ( *pText )
{
int nd = NextNode ( r, *pText++ );
if ( nd==-1 )
return -1;
r = nd;
}
return NextNode ( r, AOT_MORPH_ANNOT_CHAR ); // passing annotation char
}
void CMorphAutomat::GetInnerMorphInfos ( const BYTE * pText, DWORD * Infos ) const
{
*Infos = AOT_NOFORM;
int r = FindStringAndPassAnnotChar ( pText );
if ( r==-1 )
return;
// recursively get all interpretations
const int MAX_DEPTH = 32;
int iLevel = 0;
BYTE sPath[MAX_DEPTH];
int iChild[MAX_DEPTH];
int iChildMax[MAX_DEPTH];
iChild[0] = m_pNodes[r].GetChildrenStart();
iChildMax[0] = m_pNodes[r+1].GetChildrenStart();
while ( iLevel>=0 )
{
while ( iChild[iLevel]<iChildMax[iLevel] )
{
CMorphAutomRelation Rel = m_pRelations[iChild[iLevel]];
int NodeNo = Rel.GetChildNo();
sPath[iLevel] = Rel.GetRelationalChar();
iChild[iLevel]++;
if ( m_pNodes[NodeNo].IsFinal() )
{
*Infos++ = DecodeFromAlphabet ( sPath, iLevel+1 );
} else
{
iLevel++;
assert ( iLevel<MAX_DEPTH );
iChild[iLevel] = m_pNodes[NodeNo].GetChildrenStart();
iChildMax[iLevel] = m_pNodes[NodeNo+1].GetChildrenStart();
}
}
iLevel--;
}
*Infos = AOT_NOFORM;
}
//////////////////////////////////////////////////////////////////////////
void CLemmatizer::PredictFindRecursive ( int NodeNo, BYTE * sPath, int iPath, CSphVector<CPredictTuple> & Infos ) const
{
const CMorphAutomNode & N = m_SuffixAutomat.GetNode ( NodeNo );
if ( N.IsFinal() )
{
int i = 0;
while ( i<iPath && sPath[i]!=AOT_MORPH_ANNOT_CHAR )
i++;
int j = i+1;
while ( j<iPath && sPath[j]!=AOT_MORPH_ANNOT_CHAR )
j++;
int k = j+1;
while ( k<iPath && sPath[k]!=AOT_MORPH_ANNOT_CHAR )
k++;
CPredictTuple & A = Infos.Add();
A.m_PartOfSpeechNo = (BYTE) m_SuffixAutomat.DecodeFromAlphabet ( sPath+i+1, j-i-1 );
A.m_LemmaInfoNo = m_SuffixAutomat.DecodeFromAlphabet ( sPath+j+1, k-j-1 );
A.m_ItemNo = (WORD) m_SuffixAutomat.DecodeFromAlphabet ( sPath+k+1, iPath-k-1 );
}
int Count = m_SuffixAutomat.GetChildrenCount ( NodeNo );
for ( int i=0; i<Count; i++ )
{
const CMorphAutomRelation & p = m_SuffixAutomat.GetChildren ( NodeNo )[i];
sPath[iPath] = p.GetRelationalChar();
PredictFindRecursive ( p.GetChildNo(), sPath, iPath+1, Infos );
}
}
bool CLemmatizer::PredictFind ( const BYTE * pWord, int iLen, CSphVector<CPredictTuple> & res ) const
{
// FIXME? we might not want to predict words with annot char inside
// was: if (ReversedWordForm.find(AnnotChar) != string::npos) return false;
int r = 0;
int i = 0;
const BYTE * p = pWord + iLen;
for ( ; i<iLen; i++ )
{
int nd = m_SuffixAutomat.NextNode ( r, *--p );
if ( nd==-1 )
break;
r = nd;
}
// no prediction by suffix which is less than 3
if ( i<AOT_MIN_PREDICTION_SUFFIX )
return false;
assert ( r!=-1 );
BYTE sPath[128] = {0};
PredictFindRecursive ( r, sPath, 0, res );
return true;
}
bool CLemmatizer::IsPrefix ( const BYTE * sPrefix, int iLen ) const
{
// empty prefix is a prefix
if ( !iLen )
return true;
if ( iLen>=MAX_PREFIX_LEN || m_PrefixLen[iLen]<0 )
return false;
const BYTE * p = &m_PrefixBlob [ m_PrefixLen[iLen] ];
while ( *p==iLen )
{
if ( !memcmp ( p+1, sPrefix, iLen ) )
return true;
p += 1+iLen;
}
return false;
}
/// returns true if matched in dictionary, false if predicted
bool CLemmatizer::LemmatizeWord ( BYTE * pWord, DWORD * results ) const
{
constexpr bool bCap = false; // maybe when we manage to drag this all the way from tokenizer
constexpr bool bPredict = true;
// uppercase (and maybe other translations), check, and compute length
BYTE * p;
if ( m_iLang==AOT_RU )
{
for ( p = pWord; *p; p++ )
{
BYTE b = m_UC[*p];
// russian chars are in 0xC0..0xDF range
// avoid lemmatizing words with other chars in them
if ( ( b>>5 )!=6 )
{
*results = AOT_NOFORM;
return false;
}
// uppercase
*p = b;
}
} else ///< use the alphabet to reduce another letters
{
for ( p = pWord; *p; p++ )
{
BYTE b = m_UC[*p];
// english chars are in 0x61..0x7A range
// avoid lemmatizing words with other chars in them
if ( m_FormAutomat.m_Alphabet2CodeWithoutAnnotator[b]<0 )
{
*results = AOT_NOFORM;
return false;
}
// uppercase
*p = b;
}
}
int iLen = (int)( p-pWord );
// do dictionary lookup
m_FormAutomat.GetInnerMorphInfos ( pWord, results );
if ( *results!=AOT_NOFORM )
return true;
if_const ( !bPredict )
return false;
// attempt prediction by keyword suffix
// find the longest suffix that finds dictionary results
// require that suffix to be 4+ chars too
int iSuffix;
for ( iSuffix=1; iSuffix<=iLen-4; iSuffix++ )
{
m_FormAutomat.GetInnerMorphInfos ( pWord+iSuffix, results );
if ( *results!=AOT_NOFORM )
break;
}
// cancel suffix predictions with no hyphens, short enough
// known postfixes, and unknown prefixes
if ( pWord [ iSuffix-1 ]!='-'
&& ( iLen-iSuffix )<6
&& !IsPrefix ( pWord, iSuffix ) )
{
*results = AOT_NOFORM;
}
// cancel predictions by pronouns, eg [Sem'ykin'ym]
for ( DWORD * pRes=results; *pRes!=AOT_NOFORM; pRes++ )
if ( m_NPSs[ AOT_MODEL_NO ( *pRes ) ]==AOT_POS_UNKNOWN )
{
*results = AOT_NOFORM;
break;
}
// what, still no results?
if ( *results==AOT_NOFORM )
{
// attempt prediction by database
PredictByDataBase ( pWord, iLen, results, bCap );
// filter out too short flexias
DWORD * s = results;
DWORD * d = s;
while ( *s!=AOT_NOFORM )
{
const CMorphForm & F = m_FlexiaModels [ AOT_MODEL_NO(*s) ][ AOT_ITEM_NO(*s) ];
if ( F.m_FlexiaLen<iLen )
*d++ = *s;
s++;
}
*d = AOT_NOFORM;
}
return false;
}
void CLemmatizer::PredictByDataBase ( const BYTE * pWord, int iLen, DWORD * FindResults, bool is_cap ) const
{
// FIXME? handle all-consonant abbreviations anyway?
// was: if ( CheckAbbreviation ( InputWordStr, FindResults, is_cap ) ) return;
assert ( *FindResults==AOT_NOFORM );
DWORD * pOut = FindResults;
CSphVector<CPredictTuple> res;
// if the ABC is wrong this prediction yields too many variants
if ( m_FormAutomat.CheckABCWithoutAnnotator ( pWord ) )
PredictFind ( pWord, iLen, res );
// assume not more than 32 different pos
int has_nps[32];
for ( int i=0; i<32; i++ )
has_nps[i] = -1;
for ( const auto& tPredict : res )
{
BYTE PartOfSpeechNo = tPredict.m_PartOfSpeechNo;
if ( !m_bMaximalPrediction && has_nps[PartOfSpeechNo]!=-1 )
{
int iOldFreq = m_ModelFreq [ AOT_MODEL_NO ( FindResults[has_nps[PartOfSpeechNo]] ) ];
int iNewFreq = m_ModelFreq [ m_LemmaFlexiaModel [tPredict.m_LemmaInfoNo ] ];
if ( iOldFreq < iNewFreq )
FindResults [ has_nps [ PartOfSpeechNo ] ] = PredictPack ( tPredict );
continue;
}
has_nps [ PartOfSpeechNo ] = (int)( pOut-FindResults );
*pOut++ = PredictPack ( tPredict );
*pOut = AOT_NOFORM;
}
if ( has_nps[0]==-1 // no noun
|| ( is_cap && !m_bIsGerman ) ) // or can be a proper noun (except German, where all nouns are written uppercase)
{
static BYTE CriticalNounLetterPack[4] = "+++";
PredictFind ( CriticalNounLetterPack, AOT_MIN_PREDICTION_SUFFIX, res );
*pOut++ = PredictPack ( res.Last() );
*pOut = AOT_NOFORM;
}
}
bool CLemmatizer::LoadPak ( CSphReader & rd )
{
rd.Tag ( "sphinx-aot" );
int iVer = rd.UnzipInt();
if ( iVer!=1 )
return false;
rd.Tag ( "alphabet-desc" );
AlphabetDesc_t tDesc;
tDesc.m_iSize = rd.UnzipInt();
rd.GetBytes ( tDesc.m_dCode2Alpha, tDesc.m_iSize );
rd.GetBytes ( tDesc.m_dCode2AlphaWA, tDesc.m_iSize );
m_FormAutomat.InitAlphabet ( tDesc );
m_SuffixAutomat.InitAlphabet ( tDesc );
rd.Tag ( "uc-table" );
rd.GetBytes ( m_UC, 256 );
// caching forms can help a lot (from 4% with 256K cache to 13% with 110M cache)
rd.Tag ( "forms-automaton" );
m_FormAutomat.LoadPak ( rd, g_iCacheSize );
rd.Tag ( "flexia-models" );
m_FlexiaModels.Resize ( rd.UnzipInt() );
ARRAY_FOREACH ( i, m_FlexiaModels )
{
m_FlexiaModels[i].Resize ( rd.UnzipInt() );
ARRAY_FOREACH ( j, m_FlexiaModels[i] )
{
CMorphForm & F = m_FlexiaModels[i][j];
F.m_FlexiaLen = (BYTE) rd.GetByte();
rd.GetBytes ( F.m_Flexia, F.m_FlexiaLen );
F.m_PrefixLen = (BYTE) rd.GetByte();
rd.GetBytes ( F.m_Prefix, F.m_PrefixLen );
F.m_POS = (BYTE) rd.GetByte();
assert ( F.m_FlexiaLen<sizeof(F.m_Flexia) );
assert ( F.m_PrefixLen<sizeof(F.m_Prefix) );
F.m_Flexia[F.m_FlexiaLen] = 0;
F.m_Prefix[F.m_PrefixLen] = 0;
}
}
rd.Tag ( "prefixes" );
for ( int i=0; i<MAX_PREFIX_LEN; i++ )
m_PrefixLen[i] = rd.UnzipInt();
m_PrefixBlob.Resize ( rd.UnzipInt() );
rd.GetBytes ( m_PrefixBlob.Begin(), m_PrefixBlob.GetLength() );
rd.Tag ( "lemma-flexia-models" );
m_LemmaFlexiaModel.Resize ( rd.UnzipInt() );
ARRAY_FOREACH ( i, m_LemmaFlexiaModel )
m_LemmaFlexiaModel[i] = (WORD) rd.UnzipInt();
// build model freqs
m_ModelFreq.Resize ( m_FlexiaModels.GetLength() );
m_ModelFreq.Fill ( 0 );
ARRAY_FOREACH ( i, m_LemmaFlexiaModel )
m_ModelFreq [ m_LemmaFlexiaModel[i] ]++;
rd.Tag ( "nps-vector" );
m_NPSs.Resize ( rd.UnzipInt() );
rd.GetBytes ( m_NPSs.Begin(), m_NPSs.GetLength() );
// caching predictions does not measurably affect performance though
rd.Tag ( "prediction-automaton" );
m_SuffixAutomat.LoadPak ( rd, 0 );
rd.Tag ( "eof" );
return !rd.GetErrorFlag();
}
//////////////////////////////////////////////////////////////////////////
// SPHINX MORPHOLOGY INTERFACE
//////////////////////////////////////////////////////////////////////////
const char* AOT_LANGUAGES[AOT_LENGTH] = {"ru", "en", "de", "uk" };
static CLemmatizer * g_pLemmatizers[AOT_LENGTH] = {0};
static CSphNamedInt g_tDictinfos[AOT_LENGTH];
void sphAotSetCacheSize ( int iCacheSize )
{
g_iCacheSize = Max ( iCacheSize, 0 );
}
static bool LoadLemmatizerUk ( CSphString & sError );
bool AotInit ( const CSphString & sDictFile, CSphString & sError, int iLang )
{
if ( g_pLemmatizers[iLang] )
return true;
if ( iLang==AOT_UK )
return LoadLemmatizerUk ( sError );
CSphAutofile rdFile;
if ( rdFile.Open ( sDictFile, SPH_O_READ, sError )<0 )
return false;
g_pLemmatizers[iLang] = new CLemmatizer ( iLang==AOT_DE );
g_pLemmatizers[iLang]->m_iLang = iLang;
CSphReader rd;
rd.SetFile ( rdFile );
if ( !g_pLemmatizers[iLang]->LoadPak(rd) )
{
sError.SetSprintf ( "failed to load lemmatizer dictionary: %s", rd.GetErrorMessage().cstr() );
SafeDelete ( g_pLemmatizers[iLang] );
return false;
}
// track dictionary crc
DWORD uCrc;
if ( !sphCalcFileCRC32 ( sDictFile.cstr(), uCrc ) )
{
sError.SetSprintf ( "failed to crc32 lemmatizer dictionary %s", sDictFile.cstr() );
SafeDelete ( g_pLemmatizers[iLang] );
return false;
}
// extract basename
const char * a = sDictFile.cstr();
const char * b = a + strlen(a) - 1;
while ( b>a && b[-1]!='/' && b[-1]!='\\' )
b--;
g_tDictinfos[iLang] = { b, (int) uCrc };
return true;
}
bool sphAotInit ( const CSphString & sDictFile, CSphString & sError, int iLang )
{
return AotInit ( sDictFile, sError, iLang );
}
static inline bool IsAlpha1251 ( BYTE c )
{
return ( c>=0xC0 || c==0xA8 || c==0xB8 );
}
static inline bool IsGermanAlpha1252 ( BYTE c )
{
if ( c==0xb5 || c==0xdf )
return true;
BYTE lc = c | 0x20;
switch ( lc )
{
case 0xe2:
case 0xe4:
case 0xe7:
case 0xe8:
case 0xe9:
case 0xea:
case 0xf1:
case 0xf4:
case 0xf6:
case 0xfb:
case 0xfc:
return true;
default:
return ( lc>0x60 && lc<0x7b );
}
}
static inline bool IsAlphaAscii ( BYTE c )
{
BYTE lc = c | 0x20;
return ( lc>0x60 && lc<0x7b );
}
enum EMMITERS {EMIT_1BYTE, EMIT_UTF8RU, EMIT_UTF8};
template < EMMITERS >
inline BYTE * Emit ( BYTE * sOut, BYTE uChar )
{
if ( uChar=='-' )
return sOut;
*sOut++ = uChar | 0x20;
return sOut;
}
template<>
inline BYTE * Emit<EMIT_UTF8RU> ( BYTE * sOut, BYTE uChar )
{
if ( uChar=='-' )
return sOut;
assert ( uChar!=0xA8 && uChar!=0xB8 ); // no country for yo
uChar |= 0x20; // lowercase, E0..FF range now
if ( uChar & 0x10 )
{
// F0..FF -> D1 80..D1 8F
*sOut++ = 0xD1;
*sOut++ = uChar - 0x70;
} else
{
// E0..EF -> D0 B0..D0 BF
*sOut++ = 0xD0;
*sOut++ = uChar - 0x30;
}
return sOut;
}
template<>
inline BYTE * Emit<EMIT_UTF8> ( BYTE * sOut, BYTE uChar )
{
if ( uChar=='-' )
return sOut;
if ( uChar!=0xDF ) // don't touch 'ss' umlaut
uChar |= 0x20;
if ( uChar & 0x80 )
{
*sOut++ = 0xC0 | (uChar>>6);
*sOut++ = 0x80 | (uChar&0x3F); // NOLINT
} else
*sOut++ = uChar;
return sOut;
}
template < EMMITERS IS_UTF8 >
inline void CreateLemma ( BYTE * sOut, const BYTE * sBase, int iBaseLen, bool bFound, const CFlexiaModel & M, const CMorphForm & F )
{
// cut the form prefix
int PrefixLen = F.m_PrefixLen;
if ( bFound || strncmp ( (const char*)sBase, F.m_Prefix, PrefixLen )==0 )
{
sBase += PrefixLen;
iBaseLen -= PrefixLen;
}
// FIXME! maybe handle these lemma wide prefixes too?
#if 0
const string & LemmPrefix = m_pParent->m_Prefixes[m_InnerAnnot.m_PrefixNo];
if ( m_bFound
|| (
( m_InputWordBase.substr ( 0, LemmPrefix.length() )==LemmPrefix ) &&
( m_InputWordBase.substr ( LemmPrefix.length(), F.m_PrefixStr.length() )==F.m_PrefixStr ) ) )
{
m_InputWordBase.erase ( 0, LemmPrefix.length()+ M.m_PrefixStr.length() );
m_bPrefixesWereCut = true;
}
#endif
// cut the form suffix and append the lemma suffix
// UNLESS this was a predicted form, and form suffix does not fully match!
// eg. word=GUBARIEVICHA, flexion=IEIVICHA, so this is not really a matching lemma
int iSuff = F.m_FlexiaLen;
if ( bFound || ( iBaseLen>=iSuff && strncmp ( (const char*)sBase+iBaseLen-iSuff, F.m_Flexia, iSuff )==0 ) )
{
// ok, found and/or suffix matches, the usual route
int iCodePoints = 0;
iBaseLen -= iSuff;
while ( iBaseLen-- && iCodePoints<SPH_MAX_WORD_LEN )
{
sOut = Emit<IS_UTF8> ( sOut, *sBase++ );
iCodePoints++;
}
int iLemmaSuff = M[0].m_FlexiaLen;
const char * sFlexia = M[0].m_Flexia;
while ( iLemmaSuff-- && iCodePoints<SPH_MAX_WORD_LEN ) // OPTIMIZE? can remove len here
{
sOut = Emit<IS_UTF8> ( sOut, *sFlexia++ );
iCodePoints++;
}
} else
{
// whoops, no suffix match, just copy and lowercase the current base
while ( iBaseLen-- )
sOut = Emit<IS_UTF8> ( sOut, *sBase++ );
}
*sOut = '\0';
}
static inline bool IsRuFreq2 ( BYTE * pWord )
{
if ( pWord[2]!=0 )
return false;
int iCode = ( ( pWord[0]<<8 ) + pWord[1] ) | 0x2020;
switch ( iCode )
{
case 0xEDE0: // na
case 0xEFEE: // po
case 0xEDE5: // ne
case 0xEEF2: // ot
case 0xE7E0: // za
case 0xEEE1: // ob
case 0xE4EE: // do
case 0xF1EE: // so
case 0xE8E7: // iz
case 0xE8F5: // ih
case 0xF8F2: // sht
case 0xF3EB: // ul
return true;
}
return false;
}
static inline bool IsEnFreq2 ( BYTE * )
{
// stub
return false;
}
static inline bool IsDeFreq2 ( BYTE * )
{
// stub
return false;
}
static inline bool IsRuFreq3 ( BYTE * pWord )
{
if ( pWord[3]!=0 )
return false;
int iCode = ( ( pWord[0]<<16 ) + ( pWord[1]<<8 ) + pWord[2] ) | 0x202020;
return ( iCode==0xE8EBE8 || iCode==0xE4EBFF || iCode==0xEFF0E8 // ili, dlya, pri
|| iCode==0xE3EEE4 || iCode==0xF7F2EE || iCode==0xE1E5E7 ); // god, chto, bez
}
static inline bool IsEnFreq3 ( BYTE * )
{
// stub
return false;
}
static inline bool IsDeFreq3 ( BYTE * )
{
// stub
return false;
}
void sphAotLemmatizeRu1251 ( BYTE * pWord, int iLen )
{
// i must be initialized
assert ( g_pLemmatizers[AOT_RU] );
// pass-through 1-char words, and non-Russian words
if ( !IsAlpha1251(*pWord) || !pWord[1] )
return;
// handle a few most frequent 2-char, 3-char pass-through words
if ( iLen==2 && IsRuFreq2 ( pWord ))
return;
if ( iLen==3 && IsRuFreq3 ( pWord ))
return;
// do lemmatizing
// input keyword moves into sForm; LemmatizeWord() will also case fold sForm
// we will generate results using sForm into pWord; so we need this extra copy
BYTE sForm[MAX_KEYWORD_BYTES];
int iFormLen = 0;
// faster than strlen and strcpy..
for ( BYTE * p=pWord; *p; )
sForm[iFormLen++] = *p++;
sForm[iFormLen] = '\0';
DWORD FindResults[12]; // max results is like 6
bool bFound = g_pLemmatizers[AOT_RU]->LemmatizeWord ( (BYTE*)sForm, FindResults );
if ( FindResults[0]==AOT_NOFORM )
return;
// pick a single form
// picks a noun, if possible, and otherwise prefers shorter forms
bool bNoun = false;
for ( int i=0; FindResults[i]!=AOT_NOFORM; i++ )
{
const CFlexiaModel & M = g_pLemmatizers[AOT_RU]->m_FlexiaModels [ AOT_MODEL_NO ( FindResults[i] ) ];
const CMorphForm & F = M [ AOT_ITEM_NO ( FindResults[i] ) ];
bool bNewNoun = ( F.m_POS==0 );
if ( i==0 || ( !bNoun && bNewNoun ) )
{
CreateLemma<EMIT_1BYTE> ( pWord, sForm, iFormLen, bFound, M, F );
bNoun = bNewNoun;
} else if ( bNoun==bNewNoun )
{
BYTE sBuf[256];
CreateLemma<EMIT_1BYTE> ( sBuf, sForm, iFormLen, bFound, M, F );
if ( strcmp ( (char*)sBuf, (char*)pWord )<0 )
strcpy ( (char*)pWord, (char*)sBuf ); // NOLINT
}
}
}
void sphAotLemmatize ( BYTE * pWord, int iLang )
{
// i must be initialized
assert ( g_pLemmatizers[iLang] );
// pass-through 1-char words, and non-Russian words
if ( !IsAlphaAscii(*pWord) || !pWord[1] )
return;
// handle a few most frequent 2-char, 3-char pass-through words
if ( iLang==AOT_EN && ( IsEnFreq2(pWord) || IsEnFreq3(pWord) ) )
return;
if ( iLang==AOT_DE && ( IsDeFreq2(pWord) || IsDeFreq3(pWord) ) )
return;
// do lemmatizing
// input keyword moves into sForm; LemmatizeWord() will also case fold sForm
// we will generate results using sForm into pWord; so we need this extra copy
BYTE sForm[MAX_KEYWORD_BYTES];
int iFormLen = 0;
// faster than strlen and strcpy..