-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinformation.js
264 lines (247 loc) · 12.5 KB
/
information.js
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
const nodejieba = require('nodejieba');
const path = require('path');
const fs = require('fs');
const log = require('electron-log');
const crypto = require('crypto');
const Enumerable = require('linq-js');
const config = require('./config');
const Db = require('./db');
const titleWeightSplit = 6;
const summaryWeightSplit = 18;
const weightMerge = (original, weight, summary = false) => original + (summary ? weight * 0.2 : weight);
const ignoreWords = [ 'pro', 'mini', 'max' ]
const ignoreTags = [ 't', 'm', 'q', 'r', 'p', 'c', 'u', 'w', 'a', 'ad', 'd', 'TIME' ]; //时间副词
const ignoreTag = ({ tag, word }) => ignoreTags.includes(tag) || ignoreWords.includes(word.toLowerCase()) || word.length < 2 || /^[\x00-\xFF]*\d+[\x00-\xFF]*$/ig.test(word);
const DEFAULT_DICT = nodejieba.DEFAULT_DICT.replace(/app\.asar(\\|\/)/ig, 'app.asar.unpacked$1');
const DEFAULT_HMM_DICT = nodejieba.DEFAULT_HMM_DICT.replace(/app\.asar(\\|\/)/ig, 'app.asar.unpacked$1');
const DEFAULT_USER_DICT = nodejieba.DEFAULT_USER_DICT.replace(/app\.asar(\\|\/)/ig, 'app.asar.unpacked$1');
const DEFAULT_IDF_DICT = nodejieba.DEFAULT_IDF_DICT.replace(/app\.asar(\\|\/)/ig, 'app.asar.unpacked$1');
const DEFAULT_STOP_WORD_DICT = nodejieba.DEFAULT_STOP_WORD_DICT.replace(/app\.asar(\\|\/)/ig, 'app.asar.unpacked$1');
nodejieba.load({
dict: DEFAULT_DICT,
hmmDict: DEFAULT_HMM_DICT,
userDict: DEFAULT_USER_DICT,
idfDict: DEFAULT_IDF_DICT,
stopWordDict: DEFAULT_STOP_WORD_DICT
})
const formatDateTime = datetime => {
if (datetime) {
if (Number.isInteger(datetime)) return datetime;
datetime = datetime.trim();
if (datetime) {
if (/^\d{1,2}:\d{2}$/ig.test(datetime)) return new Date(new Date().toLocaleDateString() + ' ' + datetime + ':00').getTime();
if (/^\d{1,2}[-/月]\d{1,2}日$/ig.test(datetime)) return new Date(new Date().getFullYear() + '/' + datetime.replace(/[-年月]/ig, '/').replace('日', '') + ' 00:00:00').getTime();
if (/^\d{1,2}[-/月]\d{1,2}日? \d{1,2}:\d{2}$/ig.test(datetime)) return new Date(new Date().getFullYear() + '/' + datetime.replace(/[-年月]/ig, '/').replace('日', '') + ':00').getTime();
if (/^(\d{2}|\d{4})[-/年]\d{1,2}[-/月]\d{1,2}日?$/ig.test(datetime)) return new Date(datetime.replace(/[-年月]/ig, '/').replace('日', '') + ' 00:00:00').getTime();
if (/^(\d{2}|\d{4})[-/年]\d{1,2}[-/月]\d{1,2}日? \d{1,2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/[-年月]/ig, '/').replace('日', '') + ':00').getTime();
if (/^(\d{2}|\d{4})[-/年]\d{1,2}[-/月]\d{1,2}日? \d{1,2}:\d{2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/[-年月]/ig, '/').replace('日', '')).getTime();
if (/^\d+天前$/ig.test(datetime)) return +Date.now() - parseInt(datetime.replace('天前', '')) * 86400000;
if (/^\d+小时前$/ig.test(datetime)) return +Date.now() - parseInt(datetime.replace('小时前', '')) * 3600000;
if (/^\d+分钟前$/ig.test(datetime)) return +Date.now() - parseInt(datetime.replace('分钟前', '')) * 60000;
if (/^\d+秒前$/ig.test(datetime)) return +Date.now() - parseInt(datetime.replace('秒前', '')) * 1000;
if ('刚刚' === datetime) return +Date.now();
let today = Math.floor(+Date.now() / 86400000) * 86400000;
let yesterday = today - 86400000;
let beforeYesterday = yesterday - 86400000;
if ('今日' === datetime || '今天' === datetime) return today;
if (/^今(日|天)\s*\d{1,2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/今(日|天)\s*/ig, new Date(today).toLocaleDateString() + ' ') + ':00').getTime();
if (/^今(日|天)\s*\d{1,2}:\d{2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/今(日|天)\s*/ig, new Date(today).toLocaleDateString() + ' ')).getTime();
if ('昨日' === datetime || '昨天' === datetime) return yesterday;
if (/^昨(日|天)\s*\d{1,2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/昨(日|天)\s*/ig, new Date(yesterday).toLocaleDateString() + ' ') + ':00').getTime();
if (/^昨(日|天)\s*\d{1,2}:\d{2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/昨(日|天)\s*/ig, new Date(yesterday).toLocaleDateString() + ' ')).getTime();
if ('前日' === datetime || '前天' === datetime) return beforeYesterday;
if (/^前(日|天)\s*\d{1,2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/前(日|天)\s*/ig, new Date(beforeYesterday).toLocaleDateString() + ' ') + ':00').getTime();
if (/^前(日|天)\s*\d{1,2}:\d{2}:\d{2}$/ig.test(datetime)) return new Date(datetime.replace(/前(日|天)\s*/ig, new Date(beforeYesterday).toLocaleDateString() + ' ')).getTime();
}
return 0;
} else {
return 0;
}
}
class Information {
constructor(url, title, summary, image, datetime, simhash = 0) {
this.url = url;
this.title = title;
this.summary = summary;
this.image = image;
this.datetime = formatDateTime(datetime);
if (!this.datetime && datetime) log.warn('错误的时间格式:' + datetime);
this.tags = this.initTags();
this.simhash = typeof simhash !== 'string' ? Information.simhash(this) : simhash;
}
initTags() {
let tags = [];
let titleWeightTags = this.title.length < titleWeightSplit ? [] : nodejieba.extract(this.title, Math.floor(this.title.length / titleWeightSplit));
for (let tag of nodejieba.tag(this.title)) {
if (!ignoreTag(tag)) {
tags.push({
...tag,
weight: titleWeightTags.filter(t => t.word === tag.word).map(t => t.weight)[0] || 0
});
}
}
if (this.summary) {
let summaryWeightTags = this.summary.length < summaryWeightSplit ? [] : nodejieba.extract(this.summary, Math.floor(this.summary.length / summaryWeightSplit));
for (let tag of nodejieba.tag(this.summary)) {
if (!ignoreTag(tag)) {
let existsTag = tags.find(t => t.word === tag.word && t.tag === tag.tag);
let weightTag = summaryWeightTags.find(t => t.word === tag.word);
if (existsTag) {
existsTag.weight = weightMerge(existsTag.weight, weightTag ? weightTag.weight : 0, true);
} else {
existsTag = tag;
existsTag.weight = weightMerge(0, weightTag ? weightTag.weight : 0, true);
tags.push(existsTag);
}
}
}
}
return tags;
}
static from(db) {
return new Information(db.u, db.t, db.s, db.i, db.m, db.h);
}
static to(information) {
return {
u: information.url,
t: information.title,
s: information.summary,
i: information.image,
m: information.datetime
// h: information.simhash
}
}
static simhash(info, size = config.similar.hash) {
// let v = 0xFFFFFFFF.toString(2).split('').map(v => 0);
// for (let i = 0; i < info.tags.length; i++) {
// let tag = info.tags[i];
// let h = Information.hash(tag.word).toString(2).split('').map(v => (v === '0' ? -1 : 1) * (Math.round((tag.weight || 0) * info.tags.length) || 1));
// for (let j = v.length - 1, k = h.length - 1; j >= 0 && k >= 0; j--, k--) {
// v[j] += h[k];
// }
// }
// let result = 0;
// for (let i = 0; i < v.length; i++) {
// result |= (v[i] > 0 ? 1 : 0) << (v.length - i - 1);
// }
// if (result < 0) {
// log.error(info.title, v, result);
// }
// return result;
let v = new Array(size * 2).fill(false).map(() => [0, 0, 0, 0]);
for (let i = 0; i < info.tags.length; i++) {
let tag = info.tags[i];
let hash = Information.hash(tag.word, size);
let weight = Math.round(Math.sqrt(tag.weight)) || 1;
for (let j = 0; j < size * 2; j++) {
for (let k = 0; k < 4; k++) {
v[j][k] += ((hash[j] >> (3 - k)) & 0x01) ? weight : -weight;
}
}
}
// log.debug(info.title, v);
for (let j = 0; j < size * 2; j++) {
let n = 0;
for (let k = 0; k < 4; k++) {
n |= v[j][k] > 0 ? 1 << (3 - k) : 0;
}
v[j] = n.toString(16);
}
// log.debug(info.title, v);
return v.join('');
}
static hash(str, size = config.similar.hash) {
// let h = 0x7FFFFFFF;
// for (let i = 0; i < str.length; i++) {
// h ^= str.charCodeAt(i) << (i * 7 % 16);
// }
// return h;
return crypto.pbkdf2Sync(str, '', 1, size, 'sha512').toString('hex').split('').map(v => Number.parseInt(v, 16));
}
static distance(x, y) {
let length = Math.min(x.length, y.length);
let maxLength = Math.max(x.length, y.length);
let distance = 0;
for (let s = 0, e = Math.min(4, length); s < length; s += 4, e = Math.min(e + 4, length)) {
distance += Information.hammingDistance(Number.parseInt(x.substring(s, e), 16), Number.parseInt(y.substring(s, e), 16));
}
return distance + (maxLength - length) * 4;
}
static hammingDistance(x, y) {
let s = x ^ y, ret = 0;
while (s) {
s &= s - 1;
ret++;
}
return ret;
}
static db = false;
static async initStorage(app) {
Information.db = await Db.create(app, 'informations', [['m', 1], 't', 's', { key: 'u', options: { unique: true } }, 'i'])
}
static async add(information) {
return (await Information.addAll([ information ])).length > 0;
}
static async addAll(informations) {
let result = [];
try {
let olds = (await Information.db.find({
m: { $gte: +Date.now() - 86400000 }
})).map(Information.from);
for (let information of informations) {
if (await Information.db.findOne({ u: information.url })) {
continue;
}
await Information.db.insert(Information.to(information));
// for (let old of olds) {
// let d = Information.distance(old.simhash, information.simhash);
// if (d <= Math.max(config.similar.hash * 4 / Math.ceil(Math.min(old.title.length / titleWeightSplit + (old.summary || '').length / summaryWeightSplit, information.title.length / titleWeightSplit + (information.summary || '').length / summaryWeightSplit) + 1), config.similar.warn)) {
// log.debug(`对比新闻相似度: ${information.title} ${information.summary || ''} # ${ information.url } # <${ information.simhash }> | ${old.title} ${old.summary || ''} # ${ old.url } # <${ old.simhash }> | 相似度: ${ d }`);
// }
// }
let near = Enumerable.firstOrDefault(olds, false, old => (Information.distance(old.simhash, information.simhash) <= Math.max(config.similar.hash * 4 / Math.ceil(Math.min(old.title.length / titleWeightSplit + (old.summary || '').length / summaryWeightSplit, information.title.length / titleWeightSplit + (information.summary || '').length / summaryWeightSplit) + 1) * config.similar.truly / config.similar.warn, config.similar.truly)));
if (near) {
let d = Information.distance(near.simhash, information.simhash);
if (d > 0) {
log.info(`出现相似新闻: ${information.title} <${ information.simhash }> | ${near.title} <${ near.simhash }> | 相似度: ${ d }`);
}
let index = result.indexOf(near);
if (index !== -1) {
if (near.title.length + (near.summary || '').length < information.title.length + (information.summary || '').length) {
//替换为内容更多的新闻
result.splice(index, 1, information);
}
}
} else {
result.push(information);
}
olds.push(information);
}
return result;
} catch(e) {
log.error(e);
return result;
}
}
static async hotTags(ignores, latest = +Date.now() - 86400000) {
ignores = ignores || [];
let now = +Date.now();
let informations = (await Information.db.find({
m: { $gte: latest }
})).map(Information.from);
// fs.writeFileSync('./informations.json.js', `let g = typeof window === 'undefined' ? module.exports : window; g['informations.json.js'] = ` + JSON.stringify(informations), 'utf-8');
log.debug(`load ${ informations.length } data from db used ${ +Date.now() - now } ms`);
now = +Date.now();
let result = Enumerable.from(informations)
.selectMany(info => info.tags)
.where(infoTag => !ignoreTag(infoTag) && !ignores.includes(infoTag.word.toLowerCase()))
.groupBy(({ word, tag }) => word + '~$~' + tag, tag => tag.weight, (key, grouping) => ({ key, word: key.split('~$~')[0], weight: grouping.reduce(weightMerge, 0) }))
.orderByDescending(tag => tag.weight)
.take(config.hot.size)
.select()
.toArray();
log.debug(`calc hot tags from ${ Enumerable.sum(informations, info => info.tags.length) } tags used ${ +Date.now() - now } ms`);
return result;
}
}
module.exports = Information;