shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
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
package com.walker.semantics.support;
 
import com.walker.infrastructure.ApplicationRuntimeException;
import com.walker.infrastructure.utils.StringUtils;
import com.walker.semantics.InputWord;
import com.walker.semantics.OwnerTextItem;
import com.walker.semantics.OwnerTextStore;
import com.walker.semantics.SemanticsManager;
import com.walker.semantics.SpeechPart;
import com.walker.semantics.TextSimilar;
import com.walker.semantics.TextSimilarEngine;
import com.walker.semantics.WordMeta;
import com.walker.semantics.util.TextSimilarComparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public abstract class AbstractTextSimilarEngine implements TextSimilarEngine {
 
    protected final transient Logger logger = LoggerFactory.getLogger(getClass());
 
    // 存储 key = 业务ID,value = 词库关键词Hash值(多个)
//    private final Map<String, Integer[]> idAndWordHashCache = new HashMap<>(256);
    // key = 业务ID,value = 原始关键词内容,逗号分隔的,回显数据使用
//    private final Map<String, String> idAndTextCache = new HashMap<>(256);
    private final TextSimilarComparator comparator = new TextSimilarComparator();
 
    // 2023-09-12,增加归属人,支持多个用户同时使用
    private final Map<String, OwnerTextStore> ownerTextStoreMap = new HashMap<>(4);
 
    @Override
    public SemanticsManager getSemanticsManager() {
        return this.semanticsManager;
    }
 
    @Override
    public List<TextSimilar> search(String[] text, String owner) {
        if(StringUtils.isEmpty(owner)){
            throw new IllegalArgumentException("owner必须输入");
        }
        if(text == null || text.length == 0){
            throw new IllegalArgumentException("text必须输入");
        }
        OwnerTextStore ownerTextStore = this.ownerTextStoreMap.get(owner);
        if(ownerTextStore == null){
//            throw new IllegalStateException("没有找到owner关键词配置数据,owner=" + owner);
            logger.warn("没有找到owner关键词配置数据,owner=" + owner);
            return null;
        }
 
        Integer[] inputHashCode = new Integer[text.length];
        for(int i=0; i<text.length; i++){
            inputHashCode[i] = text[i].hashCode();
        }
 
        List<TextSimilar> data = new ArrayList<>(8);
        TextSimilar textSimilar = null;
//        for(Map.Entry<String, Integer[]> entry : this.idAndWordHashCache.entrySet()){
        for(Map.Entry<String, Integer[]> entry : ownerTextStore.getIdAndWordHashCache().entrySet()){
            textSimilar = this.calculateOneSimilar(inputHashCode, entry.getKey(), entry.getValue(), ownerTextStore.getIdAndTextCache());
            if(textSimilar != null){
                data.add(textSimilar);
                // 如果存在完美匹配的,后面就不看了。2023-08-17
                if(textSimilar.isPerfect()){
                    break;
                }
            }
        }
 
        // 对集合排序
        Collections.sort(data, comparator);
        return data;
    }
 
    protected TextSimilar calculateOneSimilar(Integer[] wordsHash
            , String id, Integer[] userKeywordHash, Map<String, String> idAndTextCache){
        int wn = wordsHash.length;
        int rn = userKeywordHash.length;
        TextSimilar textSimilar = new TextSimilar();
        textSimilar.setId(id);
//        textSimilar.setText(this.idAndTextCache.get(id));
        textSimilar.setText(idAndTextCache.get(id));
 
        int matchSize = 0;
 
        if(wn > rn){
            // 输入多于词库
            for(Integer userHashCode : userKeywordHash){
                for(Integer inputHashCode : wordsHash){
                    if(userHashCode.intValue() == inputHashCode.intValue()){
                        matchSize ++;
                        break;
                    }
                }
            }
 
            if(matchSize == 0){
                return null;
            }
 
            if(matchSize == rn){
                // 输入的多,词库词条全命中,额外+2分
                textSimilar.setDis(rn + 20);
            } else {
                // 输入的多,词库词条半命中,额外+1分
                textSimilar.setDis(matchSize + 10);
            }
 
        } else if(wn == rn){
            // 输入等于词库
            for(Integer userHashCode : userKeywordHash){
                for(Integer inputHashCode : wordsHash){
                    if(userHashCode.intValue() == inputHashCode.intValue()){
                        matchSize ++;
                        break;
                    }
                }
            }
 
            if(matchSize == 0){
                return null;
            }
            if(matchSize == rn){
                // 输入与词库相等,词库词条全命中,额外+2分
                textSimilar.setDis(matchSize + 100);
                textSimilar.setPerfect(true);
            } else {
                // 输入与词库相等,词库词条半命中,额外+5分
                textSimilar.setDis(matchSize + 20);
            }
 
        } else if(wn < rn) {
            // 输入少于词库
            for(Integer inputHashCode : wordsHash){
                for(Integer userHashCode : userKeywordHash){
                    if(inputHashCode.intValue() == userHashCode.intValue()){
                        matchSize ++;
                        break;
                    }
                }
            }
 
            if(matchSize == 0){
                return null;
            }
            if(matchSize == wn){
                // 输入与词库相等,输入全命中,额外+2分
                textSimilar.setDis(matchSize + 80);
            } else {
                // 输入与词库相等,输入半命中,额外+5分
                textSimilar.setDis(matchSize + 20);
            }
        }
 
        return textSimilar;
    }
 
    @Override
    public void loadLibrary() {
//        List<Variable> data = this.doLoadUserLibrary();
//        if(StringUtils.isEmptyList(data)){
//            logger.warn("未加载到任何用户词库,TextSimilarEngine可能无法正常工作");
//            return;
//        }
//        String id = null;
//        for(Variable v : data){
//            id = v.getId();
//            if(this.idAndWordHashCache.get(id) != null){
//                throw new IllegalArgumentException("用户词库中已经存在该业务id = " + id);
//            }
//            this.idAndWordHashCache.put(id, SemanticsUtils.acquireWordHashCode(v.getStringValue()));
//            this.idAndTextCache.put(id, v.getStringValue());
//        }
        List<OwnerTextItem> data = this.doLoadUserLibrary();
        if(StringUtils.isEmptyList(data)){
            logger.warn("未加载到任何用户词库,TextSimilarEngine可能无法正常工作");
            return;
        }
 
        OwnerTextStore ownerTextStore = null;
        for(OwnerTextItem item : data){
            ownerTextStore = this.ownerTextStoreMap.get(item.getOwner());
            if(ownerTextStore == null){
                ownerTextStore = new OwnerTextStore(item.getOwner());
                this.ownerTextStoreMap.put(item.getOwner(), ownerTextStore);
            }
            if(ownerTextStore.getWordHashCode(item.getId()) != null){
                throw new IllegalArgumentException("用户词库中已经存在该业务id = " + item.getId() + ", owner =" + item.getOwner());
            }
            ownerTextStore.putWord(item.getId(), item.getText());
        }
    }
 
    /**
     * 业务系统加载自己的词库数据。
     * <pre>
     *     1) key = 业务ID
     *     2) value = 关键词,多个使用英文逗号分隔
     * </pre>
     * @return
     * @date 2023-08-17
     */
//    protected abstract List<Variable> doLoadUserLibrary();
    protected abstract List<OwnerTextItem> doLoadUserLibrary();
 
    @Override
    public void registerKeyword(String[] words, SpeechPart speechPart) {
        this.checkSemanticsManager();
        if(words == null || words.length == 0){
            throw new IllegalArgumentException("请设置words");
        }
        if(speechPart == null){
            speechPart = SpeechPart.MY_N;
        }
        try {
            for(String word : words){
                this.semanticsManager.registerKeyWord(0, word, speechPart);
            }
        } catch (Exception ex){
            logger.error("向词库注册关键词,出现异常:" + ex.getMessage(), ex);
            throw new ApplicationRuntimeException("向词库注册关键词,出现异常:" + ex.getMessage(), ex);
        }
    }
 
    @Override
    public void removeKeyword(String keyword) {
        this.checkSemanticsManager();
        this.semanticsManager.removeKeyWord(0, keyword);
    }
 
    @Override
    public List<WordMeta> extract(String input) {
        if(StringUtils.isEmpty(input)){
            throw new IllegalArgumentException("input必须输入");
        }
        input = input.trim().toLowerCase();
        InputWord inputWord = new InputWord(input);
        return inputWord.getWordMetaList();
    }
 
    public void setSemanticsManager(SemanticsManager semanticsManager) {
        this.semanticsManager = semanticsManager;
    }
 
    private void checkSemanticsManager(){
        if(this.semanticsManager == null){
            throw new IllegalStateException("semanticsManager必须设置");
        }
    }
 
    private SemanticsManager semanticsManager;
}