dsh-ustc-campus 0.2.14 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +74 -71
- package/dist/client.js +5946 -1061
- package/package.json +63 -24
- package/src/account-data.mjs +194 -0
- package/src/bb-actions.mjs +3 -1
- package/src/bb.mjs +15 -9
- package/src/campus-transit.mjs +58 -52
- package/src/client.mjs +74 -633
- package/src/concurrency.mjs +13 -0
- package/src/custom-feeds.mjs +519 -0
- package/src/exams.mjs +21 -7
- package/src/feed.mjs +525 -137
- package/src/grades.mjs +30 -16
- package/src/host.mjs +52 -81
- package/src/library-spaces.mjs +39 -35
- package/src/material.mjs +2268 -65
- package/src/mcp-host.mjs +56 -5
- package/src/mcp.mjs +136 -27
- package/src/recommender.mjs +1319 -0
- package/src/school.mjs +218 -154
- package/src/snapshot-cache.mjs +98 -0
- package/src/state.mjs +152 -16
- package/src/youth-actions.mjs +52 -58
- package/src/youth.mjs +55 -26
|
@@ -0,0 +1,1319 @@
|
|
|
1
|
+
import { sanitizeText } from './public-fetch.mjs';
|
|
2
|
+
|
|
3
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
4
|
+
const STORE_KEY = 'recommender';
|
|
5
|
+
const STORE_VERSION = 1;
|
|
6
|
+
|
|
7
|
+
const LONG_HALF_LIFE_MS = 45 * DAY_MS;
|
|
8
|
+
const SHORT_HALF_LIFE_MS = 5 * DAY_MS;
|
|
9
|
+
|
|
10
|
+
const MAX_LONG_TERMS = 300;
|
|
11
|
+
const MAX_SHORT_TERMS = 150;
|
|
12
|
+
const MAX_ITEM_RECORDS = 400;
|
|
13
|
+
const MAX_MUTED = 50;
|
|
14
|
+
const MAX_PINNED_INTERESTS = 24;
|
|
15
|
+
|
|
16
|
+
const DEFAULT_WEIGHTS = Object.freeze({
|
|
17
|
+
shortTerm: 0.24,
|
|
18
|
+
longTerm: 0.20,
|
|
19
|
+
courseContext: 0.18,
|
|
20
|
+
topicAffinity: 0.14,
|
|
21
|
+
sourceCtr: 0.10,
|
|
22
|
+
freshness: 0.14,
|
|
23
|
+
urgency: 0.12,
|
|
24
|
+
eventAction: 0.18
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const WEIGHT_KEYS = Object.freeze(Object.keys(DEFAULT_WEIGHTS));
|
|
28
|
+
const WEIGHT_MIN = 0.03;
|
|
29
|
+
const WEIGHT_MAX = 0.45;
|
|
30
|
+
const LEARNING_RATE = 0.04;
|
|
31
|
+
|
|
32
|
+
export const TOPIC_TAXONOMY = Object.freeze({
|
|
33
|
+
academic_course: Object.freeze({
|
|
34
|
+
id: 'academic_course',
|
|
35
|
+
label: '选课教务与培养',
|
|
36
|
+
keywords: [
|
|
37
|
+
'选课', '退课', '补选', '补考', '缓考', '重修', '期末', '期中', '课表', '教学',
|
|
38
|
+
'学分', '培养方案', '转专业', '推免', '保研', '教务', '四六级', '六级', '四级',
|
|
39
|
+
'考试', '考场', '成绩', '绩点', 'gpa', '课程', '实验课', '毕业设计', '毕业论文', '免修'
|
|
40
|
+
]
|
|
41
|
+
}),
|
|
42
|
+
research_lab: Object.freeze({
|
|
43
|
+
id: 'research_lab',
|
|
44
|
+
label: '科研与学术报告',
|
|
45
|
+
keywords: [
|
|
46
|
+
'科研', '论文', 'nature', 'science', 'cell', '实验', '量子', '大研', '大学生研究计划',
|
|
47
|
+
'学术报告', '学术论坛', '学术交流', '讲座', '报告会', '诺贝尔', '超算', '智算',
|
|
48
|
+
'瀚海学堂', '前沿', '院士', '研讨会', '课题组', '突破', '揭示', '团队', '实验室', '光钟'
|
|
49
|
+
]
|
|
50
|
+
}),
|
|
51
|
+
ai_cs: Object.freeze({
|
|
52
|
+
id: 'ai_cs',
|
|
53
|
+
label: '人工智能与计算机',
|
|
54
|
+
keywords: [
|
|
55
|
+
'人工智能', '大模型', 'llm', 'agent', '机器学习', '深度学习', '计算机', '算法',
|
|
56
|
+
'系统', '网络安全', '网络空间安全', '密码', '开源', 'linux', 'lug', '软件自由日',
|
|
57
|
+
'编程', 'ctf', 'hackergame', '数据科学', '数据结构', '操作系统', '编译', '代码',
|
|
58
|
+
'ai', 'cs', '软件', '信息安全', '芯片', '算力', '计算系统'
|
|
59
|
+
]
|
|
60
|
+
}),
|
|
61
|
+
competition: Object.freeze({
|
|
62
|
+
id: 'competition',
|
|
63
|
+
label: '学科竞赛与双创',
|
|
64
|
+
keywords: [
|
|
65
|
+
'大赛', '竞赛', '挑战杯', '互联网+', '数学建模', 'robogame', '创新创业', '大创',
|
|
66
|
+
'编程竞赛', '节能减排', '创新应用', '技能大赛', '获奖', '佳绩', '参赛', '初赛', '决赛', '创新'
|
|
67
|
+
]
|
|
68
|
+
}),
|
|
69
|
+
scholarship: Object.freeze({
|
|
70
|
+
id: 'scholarship',
|
|
71
|
+
label: '奖学金与荣誉评优',
|
|
72
|
+
keywords: [
|
|
73
|
+
'奖学金', '郭沫若', '国家奖学金', '宝钢', '评优', '荣誉', '助学金', '资助',
|
|
74
|
+
'六有大学生', '自强之星', '奋进奖学金', '优秀学生', '拟推荐', '初评', '答辩', '表彰'
|
|
75
|
+
]
|
|
76
|
+
}),
|
|
77
|
+
exchange: Object.freeze({
|
|
78
|
+
id: 'exchange',
|
|
79
|
+
label: '国际交流与访学',
|
|
80
|
+
keywords: [
|
|
81
|
+
'国际交流', '海外', '交换', '暑期学校', '寒期学校', 'c9', '访学', '出国',
|
|
82
|
+
'港澳台', 'csc', '全球合作', '国际会议', '联合培养', '留学', '外事', '全球化'
|
|
83
|
+
]
|
|
84
|
+
}),
|
|
85
|
+
career: Object.freeze({
|
|
86
|
+
id: 'career',
|
|
87
|
+
label: '就业实习与宣讲',
|
|
88
|
+
keywords: [
|
|
89
|
+
'招聘', '宣讲会', '实习', '就业', '校招', '内推', '求职', '双选会', '面试', 'offer', '简历'
|
|
90
|
+
]
|
|
91
|
+
}),
|
|
92
|
+
campus_life: Object.freeze({
|
|
93
|
+
id: 'campus_life',
|
|
94
|
+
label: '校园生活与服务',
|
|
95
|
+
keywords: [
|
|
96
|
+
'校医院', '门诊', '医保', '体检', '专家', '坐诊', '排班', '停水', '停电', '断网',
|
|
97
|
+
'网络维护', '校园网', '交通', '非机动车', '保卫', '安全', '财务', '报销', '劳务费',
|
|
98
|
+
'预算', '图书馆', '研讨室', '班车', '食堂', '宿舍', '一网通办', '高频业务', '服务指南', '就医'
|
|
99
|
+
]
|
|
100
|
+
}),
|
|
101
|
+
activity_club: Object.freeze({
|
|
102
|
+
id: 'activity_club',
|
|
103
|
+
label: '社团文化与二课活动',
|
|
104
|
+
keywords: [
|
|
105
|
+
'二课', '第二课堂', '社团', '志愿', '宣介会', '文艺', '演出', '体育', '武术',
|
|
106
|
+
'运动会', '团委', '学生会', '文化节', '团校', '骨干培训', '文化驿站', '小聚', '打卡', '放映会'
|
|
107
|
+
]
|
|
108
|
+
}),
|
|
109
|
+
college_sgy: Object.freeze({
|
|
110
|
+
id: 'college_sgy',
|
|
111
|
+
label: '少年班学院',
|
|
112
|
+
keywords: ['少年班', '少院', 'sgy']
|
|
113
|
+
}),
|
|
114
|
+
college_cs_ai: Object.freeze({
|
|
115
|
+
id: 'college_cs_ai',
|
|
116
|
+
label: '信息与智能学部院系',
|
|
117
|
+
keywords: [
|
|
118
|
+
'计算机学院', '计算机科学与技术', '人工智能与数据科学', '网络空间安全',
|
|
119
|
+
'信息科学技术', '信智', '电子工程', '自动化', '微电子', '通信', '信号处理', '电路'
|
|
120
|
+
]
|
|
121
|
+
}),
|
|
122
|
+
college_sci_eng: Object.freeze({
|
|
123
|
+
id: 'college_sci_eng',
|
|
124
|
+
label: '数理化生工院系',
|
|
125
|
+
keywords: [
|
|
126
|
+
'物理', '力学', '电磁', '热学', '光学', '天文', '数学', '微积分', '线性代数',
|
|
127
|
+
'概率论', '分析', '化学', '材料', '生命科学', '生物', '医学', '工程科学', '地球', '空间科学'
|
|
128
|
+
]
|
|
129
|
+
})
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
export const TOPIC_IDS = Object.freeze(Object.keys(TOPIC_TAXONOMY));
|
|
133
|
+
|
|
134
|
+
const CATEGORY_DEFAULT_TOPICS = Object.freeze({
|
|
135
|
+
academic: ['academic_course'],
|
|
136
|
+
research: ['research_lab'],
|
|
137
|
+
exchange: ['exchange'],
|
|
138
|
+
student: ['scholarship', 'campus_life'],
|
|
139
|
+
activity: ['activity_club'],
|
|
140
|
+
lecture: ['research_lab', 'activity_club'],
|
|
141
|
+
tech: ['ai_cs', 'activity_club'],
|
|
142
|
+
service: ['campus_life'],
|
|
143
|
+
campus: []
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const SOURCE_DEFAULT_TOPICS = Object.freeze({
|
|
147
|
+
sgy: ['college_sgy'],
|
|
148
|
+
saids: ['ai_cs', 'college_cs_ai'],
|
|
149
|
+
cybersec: ['ai_cs', 'college_cs_ai'],
|
|
150
|
+
'cs-dynamic': ['ai_cs', 'college_cs_ai'],
|
|
151
|
+
sist: ['college_cs_ai'],
|
|
152
|
+
lug: ['ai_cs', 'activity_club'],
|
|
153
|
+
'lug-news': ['ai_cs', 'activity_club'],
|
|
154
|
+
ustcnet: ['campus_life', 'ai_cs'],
|
|
155
|
+
hospital: ['campus_life'],
|
|
156
|
+
bwc: ['campus_life'],
|
|
157
|
+
finance: ['campus_life'],
|
|
158
|
+
oic: ['exchange'],
|
|
159
|
+
'teach-exchange': ['exchange', 'academic_course'],
|
|
160
|
+
'teach-exam': ['academic_course'],
|
|
161
|
+
teach: ['academic_course'],
|
|
162
|
+
'teach-info': ['academic_course'],
|
|
163
|
+
'news-research': ['research_lab'],
|
|
164
|
+
'library-lecture': ['research_lab', 'activity_club']
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const URGENCY_TERMS = Object.freeze([
|
|
168
|
+
{ term: '紧急', score: 1.0 },
|
|
169
|
+
{ term: '停水', score: 0.95 },
|
|
170
|
+
{ term: '停电', score: 0.95 },
|
|
171
|
+
{ term: '断网', score: 0.95 },
|
|
172
|
+
{ term: '网络维护', score: 0.85 },
|
|
173
|
+
{ term: '维护', score: 0.65 },
|
|
174
|
+
{ term: '最后提交', score: 0.9 },
|
|
175
|
+
{ term: '截止', score: 0.85 },
|
|
176
|
+
{ term: '补选', score: 0.8 },
|
|
177
|
+
{ term: '选课', score: 0.75 },
|
|
178
|
+
{ term: '考试', score: 0.7 },
|
|
179
|
+
{ term: '考场', score: 0.75 },
|
|
180
|
+
{ term: '排班', score: 0.65 },
|
|
181
|
+
{ term: '报名', score: 0.6 },
|
|
182
|
+
{ term: '申报', score: 0.6 },
|
|
183
|
+
{ term: '答辩', score: 0.65 },
|
|
184
|
+
{ term: '公示', score: 0.5 },
|
|
185
|
+
{ term: '预约', score: 0.55 },
|
|
186
|
+
{ term: '通知', score: 0.25 }
|
|
187
|
+
]);
|
|
188
|
+
|
|
189
|
+
const STOP_WORDS = new Set([
|
|
190
|
+
'关于', '通知', '公告', '中国', '科学', '技术', '大学', '中国科大', '中国科学技术大学',
|
|
191
|
+
'我校', '学校', '举办', '开展', '有关', '工作', '事项', '名单', '公示', '相关',
|
|
192
|
+
'年度', '学年', '学期', '学院', '中心', '部门', '进行', '组织', '公布', '发布',
|
|
193
|
+
'进一步', '加强', '做好', '召开', '安排', '计划', '活动', '信息', '服务', '最新',
|
|
194
|
+
'第一', '第二', '第三', '第四', '第五', '一批', '二批', '首批', '汇总', '常见'
|
|
195
|
+
]);
|
|
196
|
+
|
|
197
|
+
const DRY_ADMIN_RE = /(?:预算|询价|采购|增值税|资金存放|竞争性选择|招投标|废旧|废弃非机动车)/;
|
|
198
|
+
|
|
199
|
+
const DICT_TERMS = Object.freeze(
|
|
200
|
+
[...new Set(Object.values(TOPIC_TAXONOMY).flatMap((topic) => topic.keywords.map((kw) => kw.toLowerCase())))]
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
function clamp(value, min, max) {
|
|
204
|
+
return Math.min(max, Math.max(min, value));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function sigmoid(x) {
|
|
208
|
+
if (x >= 20) return 1;
|
|
209
|
+
if (x <= -20) return 0;
|
|
210
|
+
return 1 / (1 + Math.exp(-x));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function decayFactor(ageMs, halfLifeMs) {
|
|
214
|
+
if (!Number.isFinite(ageMs) || ageMs <= 0) return 1;
|
|
215
|
+
return Math.pow(0.5, ageMs / halfLifeMs);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function parseDateMs(dateText) {
|
|
219
|
+
if (typeof dateText !== 'string') return null;
|
|
220
|
+
const match = dateText.match(/(\d{4})-(\d{1,2})-(\d{1,2})/);
|
|
221
|
+
if (!match) return null;
|
|
222
|
+
const year = Number(match[1]);
|
|
223
|
+
const month = Number(match[2]);
|
|
224
|
+
const day = Number(match[3]);
|
|
225
|
+
const ms = Date.UTC(year, month - 1, day) - 8 * 60 * 60 * 1000;
|
|
226
|
+
return Number.isFinite(ms) ? ms : null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Hybrid tokenizer: ASCII/alphanumeric words, curated USTC campus terms,
|
|
231
|
+
* and filtered Chinese bigrams for open-vocabulary matching.
|
|
232
|
+
*/
|
|
233
|
+
export function tokenize(rawText) {
|
|
234
|
+
const text = sanitizeText(String(rawText ?? ''), 600).toLowerCase();
|
|
235
|
+
if (!text) return [];
|
|
236
|
+
|
|
237
|
+
const tokens = new Set();
|
|
238
|
+
|
|
239
|
+
for (const match of text.matchAll(/[a-z0-9][a-z0-9+.#-]{1,23}/g)) {
|
|
240
|
+
const word = match[0].replace(/^[.-]+|[.-]+$/g, '');
|
|
241
|
+
if (word.length >= 2 && !/^\d{4}$/.test(word) && !/^\d{1,2}$/.test(word)) {
|
|
242
|
+
tokens.add(word);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
for (const term of DICT_TERMS) {
|
|
247
|
+
if (text.includes(term)) tokens.add(term);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
for (const match of text.matchAll(/[\u4e00-\u9fff]{2,}/g)) {
|
|
251
|
+
const seg = match[0];
|
|
252
|
+
if (seg.length <= 4 && !STOP_WORDS.has(seg)) {
|
|
253
|
+
tokens.add(seg);
|
|
254
|
+
}
|
|
255
|
+
for (let i = 0; i < seg.length - 1; i += 1) {
|
|
256
|
+
const bg = seg.slice(i, i + 2);
|
|
257
|
+
if (!STOP_WORDS.has(bg)) tokens.add(bg);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return [...tokens];
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Normalize a title for cross-source near-duplicate clustering. */
|
|
265
|
+
export function normalizeForDedup(title) {
|
|
266
|
+
let text = sanitizeText(String(title ?? ''), 300).toLowerCase();
|
|
267
|
+
text = text
|
|
268
|
+
.replace(/中国科学技术大学|中国科大|我校/g, '')
|
|
269
|
+
.replace(/20\d{2}\s*[—–\-至]\s*20\d{2}\s*学?年?/g, '')
|
|
270
|
+
.replace(/20\d{2}\s*年?/g, '')
|
|
271
|
+
.replace(/^关于/, '')
|
|
272
|
+
.replace(/(?:的)?(?:通知|公告|公示|预告|报名通知|评选通知|申报通知)$/, '')
|
|
273
|
+
.replace(/[\s\-_—–·•::,,.。!!??()()【】\[\]「」『』《》“”"'‘’/\\|]/g, '');
|
|
274
|
+
return text;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function charBigrams(str) {
|
|
278
|
+
const set = new Set();
|
|
279
|
+
if (!str) return set;
|
|
280
|
+
if (str.length <= 2) {
|
|
281
|
+
set.add(str);
|
|
282
|
+
return set;
|
|
283
|
+
}
|
|
284
|
+
for (let i = 0; i < str.length - 1; i += 1) {
|
|
285
|
+
set.add(str.slice(i, i + 2));
|
|
286
|
+
}
|
|
287
|
+
return set;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function jaccardSet(a, b) {
|
|
291
|
+
if (!a || !b || a.size === 0 || b.size === 0) return 0;
|
|
292
|
+
let intersection = 0;
|
|
293
|
+
const small = a.size <= b.size ? a : b;
|
|
294
|
+
const large = small === a ? b : a;
|
|
295
|
+
for (const key of small) {
|
|
296
|
+
if (large.has(key)) intersection += 1;
|
|
297
|
+
}
|
|
298
|
+
const union = a.size + b.size - intersection;
|
|
299
|
+
return union > 0 ? intersection / union : 0;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Extract topics, tokens, dedup signature, urgency and freshness for an item. */
|
|
303
|
+
export function extractItemFeatures(item, sourceMeta = null, nowMs = Date.now()) {
|
|
304
|
+
const sourceId = item?.source ?? '';
|
|
305
|
+
const category = item?.category ?? sourceMeta?.category ?? 'campus';
|
|
306
|
+
const kind = sourceMeta?.kind ?? (item?.start != null ? 'event' : 'news');
|
|
307
|
+
const collegeTags = Array.isArray(sourceMeta?.collegeTags) ? sourceMeta.collegeTags : [];
|
|
308
|
+
const rawHaystack = `${item?.title ?? ''} ${item?.location ?? ''} ${collegeTags.join(' ')}`.toLowerCase();
|
|
309
|
+
|
|
310
|
+
const tokens = tokenize(rawHaystack);
|
|
311
|
+
const tokenSet = new Set(tokens);
|
|
312
|
+
|
|
313
|
+
const topicScores = new Map();
|
|
314
|
+
for (const topic of Object.values(TOPIC_TAXONOMY)) {
|
|
315
|
+
let hits = 0;
|
|
316
|
+
for (const kw of topic.keywords) {
|
|
317
|
+
if (rawHaystack.includes(kw.toLowerCase())) hits += 1;
|
|
318
|
+
}
|
|
319
|
+
if (hits > 0) topicScores.set(topic.id, hits);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
for (const tid of SOURCE_DEFAULT_TOPICS[sourceId] ?? []) {
|
|
323
|
+
topicScores.set(tid, (topicScores.get(tid) ?? 0) + 0.75);
|
|
324
|
+
}
|
|
325
|
+
if (topicScores.size === 0) {
|
|
326
|
+
for (const tid of CATEGORY_DEFAULT_TOPICS[category] ?? []) {
|
|
327
|
+
topicScores.set(tid, 0.5);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const topics = [...topicScores.entries()]
|
|
331
|
+
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
332
|
+
.slice(0, 3)
|
|
333
|
+
.map(([id]) => id);
|
|
334
|
+
|
|
335
|
+
let urgency = 0;
|
|
336
|
+
for (const { term, score } of URGENCY_TERMS) {
|
|
337
|
+
if (rawHaystack.includes(term) && score > urgency) urgency = score;
|
|
338
|
+
}
|
|
339
|
+
if (kind === 'notice' && urgency < 0.25) urgency = 0.25;
|
|
340
|
+
|
|
341
|
+
let freshness = 0.35;
|
|
342
|
+
const itemEpoch = item?.start ?? parseDateMs(item?.date);
|
|
343
|
+
if (kind === 'event') {
|
|
344
|
+
if (item?.past) {
|
|
345
|
+
freshness = 0;
|
|
346
|
+
} else if (item?.start != null) {
|
|
347
|
+
const daysUntil = (item.start - nowMs) / DAY_MS;
|
|
348
|
+
if (daysUntil <= 0) freshness = 1.0;
|
|
349
|
+
else if (daysUntil <= 3) freshness = 0.98;
|
|
350
|
+
else if (daysUntil <= 7) freshness = 0.88;
|
|
351
|
+
else if (daysUntil <= 14) freshness = 0.72;
|
|
352
|
+
else freshness = Math.max(0.35, 0.72 * decayFactor((daysUntil - 14) * DAY_MS, 21 * DAY_MS));
|
|
353
|
+
} else {
|
|
354
|
+
freshness = 0.45;
|
|
355
|
+
}
|
|
356
|
+
} else if (itemEpoch != null) {
|
|
357
|
+
const ageMs = Math.max(0, nowMs - itemEpoch);
|
|
358
|
+
const halfLife = urgency >= 0.65 ? 4 * DAY_MS : 10 * DAY_MS;
|
|
359
|
+
freshness = decayFactor(ageMs, halfLife);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const dedupKey = normalizeForDedup(item?.title ?? '');
|
|
363
|
+
const dedupBigrams = charBigrams(dedupKey);
|
|
364
|
+
|
|
365
|
+
return {
|
|
366
|
+
sourceId,
|
|
367
|
+
category,
|
|
368
|
+
kind,
|
|
369
|
+
tokens,
|
|
370
|
+
tokenSet,
|
|
371
|
+
topics,
|
|
372
|
+
urgency,
|
|
373
|
+
freshness,
|
|
374
|
+
itemEpoch,
|
|
375
|
+
dedupKey,
|
|
376
|
+
dedupBigrams,
|
|
377
|
+
rawHaystack
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Build a zero-click cold-start user context profile from courses, saved events, and explicit query interests. */
|
|
382
|
+
export function buildUserContextProfile(context = {}) {
|
|
383
|
+
const courseTitles = Array.isArray(context?.courseTitles) ? context.courseTitles : [];
|
|
384
|
+
const savedTitles = Array.isArray(context?.savedTitles) ? context.savedTitles : [];
|
|
385
|
+
const queryInterests = Array.isArray(context?.queryInterests) ? context.queryInterests : [];
|
|
386
|
+
const pinnedInterests = Array.isArray(context?.pinnedInterests) ? context.pinnedInterests : [];
|
|
387
|
+
|
|
388
|
+
const termWeights = new Map();
|
|
389
|
+
const topicWeights = new Map();
|
|
390
|
+
|
|
391
|
+
const ingest = (texts, baseWeight) => {
|
|
392
|
+
for (const raw of texts) {
|
|
393
|
+
const text = sanitizeText(String(raw ?? ''), 200).toLowerCase();
|
|
394
|
+
if (!text) continue;
|
|
395
|
+
for (const tok of tokenize(text)) {
|
|
396
|
+
termWeights.set(tok, Math.min(3, (termWeights.get(tok) ?? 0) + baseWeight));
|
|
397
|
+
}
|
|
398
|
+
for (const topic of Object.values(TOPIC_TAXONOMY)) {
|
|
399
|
+
for (const kw of topic.keywords) {
|
|
400
|
+
if (text.includes(kw.toLowerCase())) {
|
|
401
|
+
topicWeights.set(topic.id, Math.min(3, (topicWeights.get(topic.id) ?? 0) + baseWeight));
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
ingest(courseTitles, 1.0);
|
|
410
|
+
ingest(savedTitles, 0.9);
|
|
411
|
+
ingest(pinnedInterests, 1.4);
|
|
412
|
+
ingest(queryInterests, 1.8);
|
|
413
|
+
|
|
414
|
+
return {
|
|
415
|
+
termWeights,
|
|
416
|
+
topicWeights,
|
|
417
|
+
queryInterests: queryInterests
|
|
418
|
+
.map((t) => sanitizeText(String(t ?? ''), 60))
|
|
419
|
+
.filter(Boolean),
|
|
420
|
+
pinnedInterests: pinnedInterests
|
|
421
|
+
.map((t) => sanitizeText(String(t ?? ''), 60))
|
|
422
|
+
.filter(Boolean),
|
|
423
|
+
hasCourseContext: courseTitles.length > 0 || savedTitles.length > 0
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function emptyState() {
|
|
428
|
+
return {
|
|
429
|
+
version: STORE_VERSION,
|
|
430
|
+
longTermTerms: {},
|
|
431
|
+
shortTermTerms: {},
|
|
432
|
+
sources: {},
|
|
433
|
+
topics: {},
|
|
434
|
+
items: {},
|
|
435
|
+
mutedSources: [],
|
|
436
|
+
mutedTopics: [],
|
|
437
|
+
pinnedInterests: [],
|
|
438
|
+
weights: { ...DEFAULT_WEIGHTS },
|
|
439
|
+
stats: {
|
|
440
|
+
totalImpressions: 0,
|
|
441
|
+
totalPositive: 0,
|
|
442
|
+
totalNegative: 0,
|
|
443
|
+
updates: 0
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function pruneMapByScore(record, maxEntries, nowMs, halfLifeMs) {
|
|
449
|
+
const entries = Object.entries(record);
|
|
450
|
+
if (entries.length <= maxEntries) return record;
|
|
451
|
+
entries.sort((a, b) => {
|
|
452
|
+
const scoreA = Math.abs(a[1].weight) * decayFactor(nowMs - (a[1].updatedAt ?? nowMs), halfLifeMs);
|
|
453
|
+
const scoreB = Math.abs(b[1].weight) * decayFactor(nowMs - (b[1].updatedAt ?? nowMs), halfLifeMs);
|
|
454
|
+
return scoreB - scoreA;
|
|
455
|
+
});
|
|
456
|
+
return Object.fromEntries(entries.slice(0, maxEntries));
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function pruneItems(itemsRecord, maxEntries) {
|
|
460
|
+
const entries = Object.entries(itemsRecord);
|
|
461
|
+
if (entries.length <= maxEntries) return itemsRecord;
|
|
462
|
+
entries.sort((a, b) => {
|
|
463
|
+
const prioA = (a[1].disliked ? 1e13 : 0) + (a[1].lastUpdatedAt ?? a[1].lastShownAt ?? 0);
|
|
464
|
+
const prioB = (b[1].disliked ? 1e13 : 0) + (b[1].lastUpdatedAt ?? b[1].lastShownAt ?? 0);
|
|
465
|
+
return prioB - prioA;
|
|
466
|
+
});
|
|
467
|
+
return Object.fromEntries(entries.slice(0, maxEntries));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function normalizeLoadedState(raw) {
|
|
471
|
+
const state = emptyState();
|
|
472
|
+
if (!raw || typeof raw !== 'object') return state;
|
|
473
|
+
|
|
474
|
+
const copyTermMap = (src, max) => {
|
|
475
|
+
if (!src || typeof src !== 'object') return {};
|
|
476
|
+
const out = {};
|
|
477
|
+
for (const [k, v] of Object.entries(src).slice(0, max)) {
|
|
478
|
+
const key = sanitizeText(k, 60).toLowerCase();
|
|
479
|
+
if (!key || !v || typeof v !== 'object' || !Number.isFinite(v.weight)) continue;
|
|
480
|
+
out[key] = {
|
|
481
|
+
weight: clamp(v.weight, -10, 10),
|
|
482
|
+
updatedAt: Number.isFinite(v.updatedAt) ? v.updatedAt : 0
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
return out;
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
const copyStatMap = (src, max) => {
|
|
489
|
+
if (!src || typeof src !== 'object') return {};
|
|
490
|
+
const out = {};
|
|
491
|
+
for (const [k, v] of Object.entries(src).slice(0, max)) {
|
|
492
|
+
const key = sanitizeText(k, 60);
|
|
493
|
+
if (!key || !v || typeof v !== 'object') continue;
|
|
494
|
+
out[key] = {
|
|
495
|
+
impressions: Math.max(0, Number(v.impressions) || 0),
|
|
496
|
+
positive: Math.max(0, Number(v.positive) || 0),
|
|
497
|
+
negative: Math.max(0, Number(v.negative) || 0),
|
|
498
|
+
updatedAt: Number.isFinite(v.updatedAt) ? v.updatedAt : 0
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
return out;
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
state.longTermTerms = copyTermMap(raw.longTermTerms, MAX_LONG_TERMS);
|
|
505
|
+
state.shortTermTerms = copyTermMap(raw.shortTermTerms, MAX_SHORT_TERMS);
|
|
506
|
+
state.sources = copyStatMap(raw.sources, 100);
|
|
507
|
+
state.topics = copyStatMap(raw.topics, 50);
|
|
508
|
+
|
|
509
|
+
if (raw.items && typeof raw.items === 'object') {
|
|
510
|
+
for (const [id, rec] of Object.entries(raw.items).slice(0, MAX_ITEM_RECORDS)) {
|
|
511
|
+
const cleanId = sanitizeText(id, 200);
|
|
512
|
+
if (!cleanId || !rec || typeof rec !== 'object') continue;
|
|
513
|
+
state.items[cleanId] = {
|
|
514
|
+
impressions: Math.max(0, Number(rec.impressions) || 0),
|
|
515
|
+
lastShownAt: Number.isFinite(rec.lastShownAt) ? rec.lastShownAt : 0,
|
|
516
|
+
opened: Math.max(0, Number(rec.opened) || 0),
|
|
517
|
+
saved: rec.saved === true,
|
|
518
|
+
liked: rec.liked === true,
|
|
519
|
+
disliked: rec.disliked === true,
|
|
520
|
+
dwellMs: Math.max(0, Number(rec.dwellMs) || 0),
|
|
521
|
+
fatigueApplied: rec.fatigueApplied === true,
|
|
522
|
+
lastUpdatedAt: Number.isFinite(rec.lastUpdatedAt) ? rec.lastUpdatedAt : 0
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
const copyStringList = (arr, max) => {
|
|
528
|
+
if (!Array.isArray(arr)) return [];
|
|
529
|
+
const seen = new Set();
|
|
530
|
+
const out = [];
|
|
531
|
+
for (const val of arr) {
|
|
532
|
+
const clean = sanitizeText(String(val ?? ''), 60);
|
|
533
|
+
if (!clean || seen.has(clean.toLowerCase())) continue;
|
|
534
|
+
seen.add(clean.toLowerCase());
|
|
535
|
+
out.push(clean);
|
|
536
|
+
if (out.length >= max) break;
|
|
537
|
+
}
|
|
538
|
+
return out;
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
state.mutedSources = copyStringList(raw.mutedSources, MAX_MUTED);
|
|
542
|
+
state.mutedTopics = copyStringList(raw.mutedTopics, MAX_MUTED);
|
|
543
|
+
state.pinnedInterests = copyStringList(raw.pinnedInterests, MAX_PINNED_INTERESTS);
|
|
544
|
+
|
|
545
|
+
if (raw.weights && typeof raw.weights === 'object') {
|
|
546
|
+
for (const key of WEIGHT_KEYS) {
|
|
547
|
+
if (Number.isFinite(raw.weights[key])) {
|
|
548
|
+
state.weights[key] = clamp(raw.weights[key], WEIGHT_MIN, WEIGHT_MAX);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if (raw.stats && typeof raw.stats === 'object') {
|
|
554
|
+
state.stats = {
|
|
555
|
+
totalImpressions: Math.max(0, Number(raw.stats.totalImpressions) || 0),
|
|
556
|
+
totalPositive: Math.max(0, Number(raw.stats.totalPositive) || 0),
|
|
557
|
+
totalNegative: Math.max(0, Number(raw.stats.totalNegative) || 0),
|
|
558
|
+
updates: Math.max(0, Number(raw.stats.updates) || 0)
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
return state;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function memoryStore() {
|
|
566
|
+
const map = new Map();
|
|
567
|
+
return {
|
|
568
|
+
read: (k) => map.get(k),
|
|
569
|
+
write: (k, v) => map.set(k, v)
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Create a persistent local multi-stage recommender.
|
|
575
|
+
*/
|
|
576
|
+
export function createRecommender(options = {}) {
|
|
577
|
+
const fallback = memoryStore();
|
|
578
|
+
const read = typeof options.read === 'function' ? options.read : fallback.read;
|
|
579
|
+
const write = typeof options.write === 'function' ? options.write : fallback.write;
|
|
580
|
+
const now = typeof options.now === 'function' ? options.now : Date.now;
|
|
581
|
+
|
|
582
|
+
let state;
|
|
583
|
+
try {
|
|
584
|
+
state = normalizeLoadedState(read(STORE_KEY));
|
|
585
|
+
} catch {
|
|
586
|
+
state = emptyState();
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function persist() {
|
|
590
|
+
try {
|
|
591
|
+
write(STORE_KEY, state);
|
|
592
|
+
} catch {
|
|
593
|
+
/* keep in-memory state working even if disk storage fails */
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function decayedTermWeight(map, term, nowMs, halfLifeMs) {
|
|
598
|
+
const entry = map[term];
|
|
599
|
+
if (!entry) return 0;
|
|
600
|
+
return entry.weight * decayFactor(nowMs - (entry.updatedAt ?? nowMs), halfLifeMs);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function addTermSignal(map, term, delta, nowMs, halfLifeMs) {
|
|
604
|
+
const existing = decayedTermWeight(map, term, nowMs, halfLifeMs);
|
|
605
|
+
const next = clamp(existing + delta, -8, 10);
|
|
606
|
+
if (Math.abs(next) < 0.02) {
|
|
607
|
+
delete map[term];
|
|
608
|
+
} else {
|
|
609
|
+
map[term] = { weight: Number(next.toFixed(4)), updatedAt: nowMs };
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function ensureStat(map, key) {
|
|
614
|
+
if (!map[key]) {
|
|
615
|
+
map[key] = { impressions: 0, positive: 0, negative: 0, updatedAt: now() };
|
|
616
|
+
}
|
|
617
|
+
return map[key];
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function ensureItem(itemId) {
|
|
621
|
+
if (!state.items[itemId]) {
|
|
622
|
+
state.items[itemId] = {
|
|
623
|
+
impressions: 0,
|
|
624
|
+
lastShownAt: 0,
|
|
625
|
+
opened: 0,
|
|
626
|
+
saved: false,
|
|
627
|
+
liked: false,
|
|
628
|
+
disliked: false,
|
|
629
|
+
dwellMs: 0,
|
|
630
|
+
fatigueApplied: false,
|
|
631
|
+
lastUpdatedAt: now()
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
return state.items[itemId];
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function bayesianCtr(stat) {
|
|
638
|
+
if (!stat) return 0.25;
|
|
639
|
+
const effectivePos = stat.positive;
|
|
640
|
+
const effectiveTotal = Math.max(stat.impressions, stat.positive + stat.negative) + stat.negative * 0.5;
|
|
641
|
+
return clamp((effectivePos + 1.0) / (effectiveTotal + 4.0), 0.02, 0.95);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function ucbBonus(impressions, totalImpressions) {
|
|
645
|
+
if (totalImpressions < 2) return impressions === 0 ? 0.08 : 0.02;
|
|
646
|
+
return Math.min(0.22, 0.11 * Math.sqrt(Math.log(totalImpressions + 2) / (impressions + 1)));
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function computeFeatureVector(item, feat, userCtx, agendaInfo, nowMs) {
|
|
650
|
+
let shortSum = 0;
|
|
651
|
+
let longSum = 0;
|
|
652
|
+
let shortHits = 0;
|
|
653
|
+
let longHits = 0;
|
|
654
|
+
const matchedUserTerms = [];
|
|
655
|
+
|
|
656
|
+
for (const tok of feat.tokens) {
|
|
657
|
+
const sw = decayedTermWeight(state.shortTermTerms, tok, nowMs, SHORT_HALF_LIFE_MS);
|
|
658
|
+
const lw = decayedTermWeight(state.longTermTerms, tok, nowMs, LONG_HALF_LIFE_MS);
|
|
659
|
+
if (sw !== 0) {
|
|
660
|
+
shortSum += sw;
|
|
661
|
+
if (sw > 0.25) shortHits += 1;
|
|
662
|
+
}
|
|
663
|
+
if (lw !== 0) {
|
|
664
|
+
longSum += lw;
|
|
665
|
+
if (lw > 0.25) longHits += 1;
|
|
666
|
+
}
|
|
667
|
+
if (sw > 0.4 || lw > 0.5) {
|
|
668
|
+
matchedUserTerms.push({ term: tok, score: sw + lw });
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const normDenom = Math.sqrt(Math.max(1, feat.tokens.length));
|
|
673
|
+
const shortTerm = clamp(0.5 + Math.tanh(shortSum / (normDenom * 1.4)) * 0.5, 0, 1);
|
|
674
|
+
const longTerm = clamp(0.5 + Math.tanh(longSum / (normDenom * 1.6)) * 0.5, 0, 1);
|
|
675
|
+
|
|
676
|
+
let ctxSum = 0;
|
|
677
|
+
const explicitHits = [];
|
|
678
|
+
for (const q of [...userCtx.queryInterests, ...userCtx.pinnedInterests]) {
|
|
679
|
+
if (feat.rawHaystack.includes(q.toLowerCase())) {
|
|
680
|
+
explicitHits.push(q);
|
|
681
|
+
ctxSum += 1.5;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
for (const tok of feat.tokens) {
|
|
685
|
+
const w = userCtx.termWeights.get(tok);
|
|
686
|
+
if (w) ctxSum += w * 0.55;
|
|
687
|
+
}
|
|
688
|
+
for (const tid of feat.topics) {
|
|
689
|
+
const tw = userCtx.topicWeights.get(tid);
|
|
690
|
+
if (tw) ctxSum += tw * 0.7;
|
|
691
|
+
}
|
|
692
|
+
const courseContext = clamp(Math.tanh(ctxSum / 2.2), 0, 1);
|
|
693
|
+
|
|
694
|
+
let topicAffinity = 0.25;
|
|
695
|
+
if (feat.topics.length > 0) {
|
|
696
|
+
const sum = feat.topics.reduce((acc, tid) => acc + bayesianCtr(state.topics[tid]), 0);
|
|
697
|
+
topicAffinity = sum / feat.topics.length;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
const sourceStat = state.sources[feat.sourceId];
|
|
701
|
+
const sourceCtr = bayesianCtr(sourceStat);
|
|
702
|
+
const freshness = feat.freshness;
|
|
703
|
+
const urgency = feat.urgency;
|
|
704
|
+
|
|
705
|
+
let eventAction = 0.25;
|
|
706
|
+
let conflicts = false;
|
|
707
|
+
if (feat.kind === 'event') {
|
|
708
|
+
if (item.past) {
|
|
709
|
+
eventAction = 0;
|
|
710
|
+
} else if (item.start != null) {
|
|
711
|
+
conflicts = agendaInfo?.overlaps?.(item) === true;
|
|
712
|
+
if (conflicts) {
|
|
713
|
+
eventAction = 0.05;
|
|
714
|
+
} else {
|
|
715
|
+
eventAction = item.secondClassroom ? 1.0 : 0.85;
|
|
716
|
+
if (item.start - nowMs <= 7 * DAY_MS) eventAction = Math.min(1.0, eventAction + 0.12);
|
|
717
|
+
}
|
|
718
|
+
} else {
|
|
719
|
+
eventAction = 0.3;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
const srcImp = sourceStat?.impressions ?? 0;
|
|
724
|
+
const topicImp = feat.topics.length > 0
|
|
725
|
+
? Math.min(...feat.topics.map((tid) => state.topics[tid]?.impressions ?? 0))
|
|
726
|
+
: 0;
|
|
727
|
+
const exploration = feat.kind === 'event' && item.past
|
|
728
|
+
? 0
|
|
729
|
+
: ucbBonus(Math.min(srcImp, topicImp), state.stats.totalImpressions);
|
|
730
|
+
|
|
731
|
+
const itemRec = state.items[item.id];
|
|
732
|
+
let fatiguePenalty = 0;
|
|
733
|
+
if (itemRec && itemRec.impressions >= 2 && itemRec.opened === 0 && !itemRec.liked && !itemRec.saved) {
|
|
734
|
+
fatiguePenalty = Math.min(0.35, 0.09 * (itemRec.impressions - 1));
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
return {
|
|
738
|
+
features: {
|
|
739
|
+
shortTerm,
|
|
740
|
+
longTerm,
|
|
741
|
+
courseContext,
|
|
742
|
+
topicAffinity,
|
|
743
|
+
sourceCtr,
|
|
744
|
+
freshness,
|
|
745
|
+
urgency,
|
|
746
|
+
eventAction
|
|
747
|
+
},
|
|
748
|
+
meta: {
|
|
749
|
+
shortHits,
|
|
750
|
+
longHits,
|
|
751
|
+
explicitHits: [...new Set(explicitHits)].slice(0, 3),
|
|
752
|
+
matchedUserTerms: matchedUserTerms
|
|
753
|
+
.sort((a, b) => b.score - a.score)
|
|
754
|
+
.map((x) => x.term)
|
|
755
|
+
.slice(0, 3),
|
|
756
|
+
conflicts,
|
|
757
|
+
exploration,
|
|
758
|
+
fatiguePenalty,
|
|
759
|
+
sourceImpressions: srcImp,
|
|
760
|
+
sourcePositive: sourceStat?.positive ?? 0
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function updateOnlineWeights(features, targetY) {
|
|
766
|
+
let z = -0.35;
|
|
767
|
+
for (const k of WEIGHT_KEYS) {
|
|
768
|
+
z += (state.weights[k] ?? DEFAULT_WEIGHTS[k]) * (features[k] ?? 0);
|
|
769
|
+
}
|
|
770
|
+
const pred = sigmoid(z);
|
|
771
|
+
const err = targetY - pred;
|
|
772
|
+
for (const k of WEIGHT_KEYS) {
|
|
773
|
+
const prev = state.weights[k] ?? DEFAULT_WEIGHTS[k];
|
|
774
|
+
const next = clamp(prev + LEARNING_RATE * err * (features[k] ?? 0), WEIGHT_MIN, WEIGHT_MAX);
|
|
775
|
+
state.weights[k] = Number(next.toFixed(4));
|
|
776
|
+
}
|
|
777
|
+
state.stats.updates += 1;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function applySignalToFeatures(item, sourceMeta, delta, targetY, nowMs) {
|
|
781
|
+
const feat = extractItemFeatures(item, sourceMeta, nowMs);
|
|
782
|
+
const termDeltaShort = delta * 0.65;
|
|
783
|
+
const termDeltaLong = delta * 0.35;
|
|
784
|
+
|
|
785
|
+
for (const tok of feat.tokens.slice(0, 24)) {
|
|
786
|
+
addTermSignal(state.shortTermTerms, tok, termDeltaShort, nowMs, SHORT_HALF_LIFE_MS);
|
|
787
|
+
addTermSignal(state.longTermTerms, tok, termDeltaLong, nowMs, LONG_HALF_LIFE_MS);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
const srcStat = ensureStat(state.sources, feat.sourceId);
|
|
791
|
+
if (delta > 0) srcStat.positive += delta;
|
|
792
|
+
else srcStat.negative += Math.abs(delta);
|
|
793
|
+
srcStat.updatedAt = nowMs;
|
|
794
|
+
|
|
795
|
+
for (const tid of feat.topics) {
|
|
796
|
+
const tStat = ensureStat(state.topics, tid);
|
|
797
|
+
if (delta > 0) tStat.positive += delta;
|
|
798
|
+
else tStat.negative += Math.abs(delta);
|
|
799
|
+
tStat.updatedAt = nowMs;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
if (targetY === 0 || targetY === 1) {
|
|
803
|
+
const { features } = computeFeatureVector(
|
|
804
|
+
item,
|
|
805
|
+
feat,
|
|
806
|
+
buildUserContextProfile({ pinnedInterests: state.pinnedInterests }),
|
|
807
|
+
null,
|
|
808
|
+
nowMs
|
|
809
|
+
);
|
|
810
|
+
updateOnlineWeights(features, targetY);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
state.shortTermTerms = pruneMapByScore(state.shortTermTerms, MAX_SHORT_TERMS, nowMs, SHORT_HALF_LIFE_MS);
|
|
814
|
+
state.longTermTerms = pruneMapByScore(state.longTermTerms, MAX_LONG_TERMS, nowMs, LONG_HALF_LIFE_MS);
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
function recordFeedback(event = {}, lookup = {}) {
|
|
818
|
+
const nowMs = now();
|
|
819
|
+
const action = sanitizeText(String(event?.action ?? ''), 32).toLowerCase();
|
|
820
|
+
const getItem = typeof lookup.getItem === 'function' ? lookup.getItem : () => null;
|
|
821
|
+
const getSourceMeta = typeof lookup.getSourceMeta === 'function' ? lookup.getSourceMeta : () => null;
|
|
822
|
+
|
|
823
|
+
if (action === 'reset') {
|
|
824
|
+
state = emptyState();
|
|
825
|
+
persist();
|
|
826
|
+
return { status: 'reset', profile: getProfile() };
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
if (action === 'mute_source' || action === 'unmute_source') {
|
|
830
|
+
const source = sanitizeText(String(event.source ?? ''), 60).toLowerCase();
|
|
831
|
+
if (!source) return { status: 'invalid', message: '请提供有效的来源 ID' };
|
|
832
|
+
const set = new Set(state.mutedSources);
|
|
833
|
+
if (action === 'mute_source') set.add(source);
|
|
834
|
+
else set.delete(source);
|
|
835
|
+
state.mutedSources = [...set].slice(0, MAX_MUTED);
|
|
836
|
+
persist();
|
|
837
|
+
return { status: action === 'mute_source' ? 'muted' : 'unmuted', source, mutedSources: [...state.mutedSources] };
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
if (action === 'mute_topic' || action === 'unmute_topic') {
|
|
841
|
+
const topic = sanitizeText(String(event.topic ?? ''), 60).toLowerCase();
|
|
842
|
+
if (!topic || !Object.hasOwn(TOPIC_TAXONOMY, topic)) {
|
|
843
|
+
return { status: 'invalid', message: '无效的话题分类', validTopics: TOPIC_IDS };
|
|
844
|
+
}
|
|
845
|
+
const set = new Set(state.mutedTopics);
|
|
846
|
+
if (action === 'mute_topic') set.add(topic);
|
|
847
|
+
else set.delete(topic);
|
|
848
|
+
state.mutedTopics = [...set].slice(0, MAX_MUTED);
|
|
849
|
+
persist();
|
|
850
|
+
return { status: action === 'mute_topic' ? 'muted' : 'unmuted', topic, mutedTopics: [...state.mutedTopics] };
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
if (action === 'set_interests') {
|
|
854
|
+
const raw = Array.isArray(event.interests)
|
|
855
|
+
? event.interests
|
|
856
|
+
: String(event.interests ?? '').split(/[,,、;;\n]/);
|
|
857
|
+
const seen = new Set();
|
|
858
|
+
const next = [];
|
|
859
|
+
for (const value of raw) {
|
|
860
|
+
const clean = sanitizeText(String(value ?? ''), 60);
|
|
861
|
+
if (!clean || seen.has(clean.toLowerCase())) continue;
|
|
862
|
+
seen.add(clean.toLowerCase());
|
|
863
|
+
next.push(clean);
|
|
864
|
+
if (next.length >= MAX_PINNED_INTERESTS) break;
|
|
865
|
+
}
|
|
866
|
+
state.pinnedInterests = next;
|
|
867
|
+
persist();
|
|
868
|
+
return { status: 'updated', pinnedInterests: [...state.pinnedInterests] };
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
if (action === 'impression') {
|
|
872
|
+
const ids = Array.isArray(event.itemIds)
|
|
873
|
+
? event.itemIds
|
|
874
|
+
: (event.itemId ? [event.itemId] : []);
|
|
875
|
+
let recorded = 0;
|
|
876
|
+
for (const rawId of ids.slice(0, 30)) {
|
|
877
|
+
const id = sanitizeText(String(rawId ?? ''), 200);
|
|
878
|
+
if (!id) continue;
|
|
879
|
+
const rec = ensureItem(id);
|
|
880
|
+
rec.impressions += 1;
|
|
881
|
+
rec.lastShownAt = nowMs;
|
|
882
|
+
rec.lastUpdatedAt = nowMs;
|
|
883
|
+
state.stats.totalImpressions += 1;
|
|
884
|
+
recorded += 1;
|
|
885
|
+
|
|
886
|
+
const item = getItem(id);
|
|
887
|
+
if (item) {
|
|
888
|
+
const sourceMeta = getSourceMeta(item.source);
|
|
889
|
+
const feat = extractItemFeatures(item, sourceMeta, nowMs);
|
|
890
|
+
const srcStat = ensureStat(state.sources, feat.sourceId);
|
|
891
|
+
srcStat.impressions += 1;
|
|
892
|
+
srcStat.updatedAt = nowMs;
|
|
893
|
+
for (const tid of feat.topics) {
|
|
894
|
+
const tStat = ensureStat(state.topics, tid);
|
|
895
|
+
tStat.impressions += 1;
|
|
896
|
+
tStat.updatedAt = nowMs;
|
|
897
|
+
}
|
|
898
|
+
if (rec.impressions >= 3 && !rec.fatigueApplied && rec.opened === 0 && !rec.liked && !rec.saved) {
|
|
899
|
+
rec.fatigueApplied = true;
|
|
900
|
+
applySignalToFeatures(item, sourceMeta, -0.45, 0, nowMs);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
state.items = pruneItems(state.items, MAX_ITEM_RECORDS);
|
|
905
|
+
persist();
|
|
906
|
+
return { status: 'recorded', action, count: recorded };
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
const itemId = sanitizeText(String(event.itemId ?? ''), 200);
|
|
910
|
+
if (!itemId) return { status: 'invalid', message: '请提供有效的资讯 ID(itemId)' };
|
|
911
|
+
const item = event.item && typeof event.item === 'object' ? event.item : getItem(itemId);
|
|
912
|
+
const sourceMeta = item ? getSourceMeta(item.source) : null;
|
|
913
|
+
const rec = ensureItem(itemId);
|
|
914
|
+
rec.lastUpdatedAt = nowMs;
|
|
915
|
+
|
|
916
|
+
if (action === 'open' || action === 'click') {
|
|
917
|
+
const dwellMs = clamp(Number(event.dwellMs) || 0, 0, 3_600_000);
|
|
918
|
+
rec.opened += 1;
|
|
919
|
+
rec.dwellMs = Math.max(rec.dwellMs, dwellMs);
|
|
920
|
+
rec.disliked = false;
|
|
921
|
+
const strength = dwellMs >= 15_000 ? 1.5 : dwellMs > 0 && dwellMs < 2_000 ? 0.25 : 1.0;
|
|
922
|
+
state.stats.totalPositive += 1;
|
|
923
|
+
if (item) applySignalToFeatures(item, sourceMeta, strength, dwellMs >= 8_000 || dwellMs === 0 ? 1 : null, nowMs);
|
|
924
|
+
} else if (action === 'dwell') {
|
|
925
|
+
const dwellMs = clamp(Number(event.dwellMs) || 0, 0, 3_600_000);
|
|
926
|
+
rec.dwellMs = Math.max(rec.dwellMs, dwellMs);
|
|
927
|
+
if (dwellMs >= 8_000 && item) {
|
|
928
|
+
const bonus = dwellMs >= 30_000 ? 1.0 : 0.55;
|
|
929
|
+
state.stats.totalPositive += 1;
|
|
930
|
+
applySignalToFeatures(item, sourceMeta, bonus, 1, nowMs);
|
|
931
|
+
}
|
|
932
|
+
} else if (action === 'save') {
|
|
933
|
+
rec.saved = true;
|
|
934
|
+
rec.disliked = false;
|
|
935
|
+
state.stats.totalPositive += 1;
|
|
936
|
+
if (item) applySignalToFeatures(item, sourceMeta, 2.2, 1, nowMs);
|
|
937
|
+
} else if (action === 'like') {
|
|
938
|
+
rec.liked = true;
|
|
939
|
+
rec.disliked = false;
|
|
940
|
+
state.stats.totalPositive += 1;
|
|
941
|
+
if (item) applySignalToFeatures(item, sourceMeta, 2.0, 1, nowMs);
|
|
942
|
+
} else if (action === 'ask') {
|
|
943
|
+
rec.opened += 1;
|
|
944
|
+
state.stats.totalPositive += 1;
|
|
945
|
+
if (item) applySignalToFeatures(item, sourceMeta, 1.2, 1, nowMs);
|
|
946
|
+
} else if (action === 'dislike') {
|
|
947
|
+
rec.disliked = true;
|
|
948
|
+
rec.liked = false;
|
|
949
|
+
state.stats.totalNegative += 1;
|
|
950
|
+
if (item) applySignalToFeatures(item, sourceMeta, -2.5, 0, nowMs);
|
|
951
|
+
} else {
|
|
952
|
+
return { status: 'invalid', message: `不支持的反馈动作:${action}` };
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
state.items = pruneItems(state.items, MAX_ITEM_RECORDS);
|
|
956
|
+
persist();
|
|
957
|
+
return { status: 'recorded', action, itemId };
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function rank(items, options = {}) {
|
|
961
|
+
const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : now();
|
|
962
|
+
const getSourceMeta = typeof options.getSourceMeta === 'function' ? options.getSourceMeta : () => null;
|
|
963
|
+
const explicitSourceFilter = options.explicitSourceFilter === true;
|
|
964
|
+
const explicitKeywordFilter = options.explicitKeywordFilter === true;
|
|
965
|
+
const agendaInfo = options.agendaInfo ?? null;
|
|
966
|
+
const dedupe = options.dedupe !== false;
|
|
967
|
+
|
|
968
|
+
const userCtx = buildUserContextProfile({
|
|
969
|
+
courseTitles: options.userContext?.courseTitles,
|
|
970
|
+
savedTitles: options.userContext?.savedTitles,
|
|
971
|
+
queryInterests: options.interests,
|
|
972
|
+
pinnedInterests: state.pinnedInterests
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
const mutedSources = new Set(state.mutedSources);
|
|
976
|
+
const mutedTopics = new Set(state.mutedTopics);
|
|
977
|
+
|
|
978
|
+
// Stage 1: Hard filter & feature extraction
|
|
979
|
+
const candidates = [];
|
|
980
|
+
for (const item of items) {
|
|
981
|
+
const rec = state.items[item.id];
|
|
982
|
+
if (rec?.disliked && !explicitKeywordFilter) continue;
|
|
983
|
+
if (!explicitSourceFilter && !explicitKeywordFilter && mutedSources.has(item.source)) continue;
|
|
984
|
+
|
|
985
|
+
const sourceMeta = getSourceMeta(item.source);
|
|
986
|
+
const feat = extractItemFeatures(item, sourceMeta, nowMs);
|
|
987
|
+
|
|
988
|
+
if (
|
|
989
|
+
!explicitSourceFilter &&
|
|
990
|
+
!explicitKeywordFilter &&
|
|
991
|
+
feat.topics.length > 0 &&
|
|
992
|
+
feat.topics.some((tid) => mutedTopics.has(tid))
|
|
993
|
+
) {
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
const { features, meta } = computeFeatureVector(item, feat, userCtx, agendaInfo, nowMs);
|
|
998
|
+
|
|
999
|
+
let rawScore = 0;
|
|
1000
|
+
for (const k of WEIGHT_KEYS) {
|
|
1001
|
+
rawScore += (state.weights[k] ?? DEFAULT_WEIGHTS[k]) * (features[k] ?? 0);
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
if (meta.explicitHits.length > 0) {
|
|
1005
|
+
rawScore += 0.35 + Math.min(0.25, (meta.explicitHits.length - 1) * 0.12);
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
const isActivity = item.intent === 'activity' || feat.kind === 'event' || item.source === 'youth-enrolling';
|
|
1009
|
+
if (isActivity && !(feat.kind === 'event' && item.past)) {
|
|
1010
|
+
rawScore += 0.12;
|
|
1011
|
+
if (item.requiresRegistration && item.remainingSlots !== 0 && item.registered !== true) {
|
|
1012
|
+
rawScore += 0.06;
|
|
1013
|
+
}
|
|
1014
|
+
if (item.source === 'youth-enrolling' && (item.registered === true || item.remainingSlots === 0)) {
|
|
1015
|
+
rawScore -= 0.08;
|
|
1016
|
+
}
|
|
1017
|
+
} else if (
|
|
1018
|
+
DRY_ADMIN_RE.test(item.title) &&
|
|
1019
|
+
meta.shortHits === 0 &&
|
|
1020
|
+
meta.longHits === 0 &&
|
|
1021
|
+
meta.explicitHits.length === 0 &&
|
|
1022
|
+
meta.sourcePositive < 1.5
|
|
1023
|
+
) {
|
|
1024
|
+
rawScore -= 0.14;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
if (feat.kind === 'event' && item.past) {
|
|
1028
|
+
rawScore -= 1.2;
|
|
1029
|
+
} else if (meta.conflicts) {
|
|
1030
|
+
rawScore -= 0.45;
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
rawScore -= meta.fatiguePenalty;
|
|
1034
|
+
rawScore += meta.exploration;
|
|
1035
|
+
|
|
1036
|
+
const channels = [];
|
|
1037
|
+
if (meta.explicitHits.length > 0 || meta.shortHits > 0 || meta.longHits > 0) channels.push('interest');
|
|
1038
|
+
if (userCtx.hasCourseContext && features.courseContext >= 0.32) channels.push('course_context');
|
|
1039
|
+
if (feat.urgency >= 0.65 && feat.freshness >= 0.35) channels.push('urgent');
|
|
1040
|
+
if (feat.kind === 'event' && !item.past && !meta.conflicts && item.start != null) channels.push('upcoming_event');
|
|
1041
|
+
if (meta.sourcePositive >= 1.5 && features.sourceCtr >= 0.35) channels.push('favorite_source');
|
|
1042
|
+
if (meta.sourceImpressions === 0 && meta.exploration >= 0.08 && !(feat.kind === 'event' && item.past)) {
|
|
1043
|
+
channels.push('exploration');
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
candidates.push({
|
|
1047
|
+
item,
|
|
1048
|
+
sourceMeta,
|
|
1049
|
+
feat,
|
|
1050
|
+
features,
|
|
1051
|
+
meta,
|
|
1052
|
+
rawScore,
|
|
1053
|
+
channels: channels.slice(0, 3),
|
|
1054
|
+
alsoIn: []
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
candidates.sort((a, b) => {
|
|
1059
|
+
if (b.rawScore !== a.rawScore) return b.rawScore - a.rawScore;
|
|
1060
|
+
const timeA = a.feat.itemEpoch ?? 0;
|
|
1061
|
+
const timeB = b.feat.itemEpoch ?? 0;
|
|
1062
|
+
if (timeA !== timeB) return timeB - timeA;
|
|
1063
|
+
return a.item.title.localeCompare(b.item.title, 'zh-CN');
|
|
1064
|
+
});
|
|
1065
|
+
|
|
1066
|
+
// Stage 2: Cross-source near-duplicate clustering
|
|
1067
|
+
let deduped = candidates;
|
|
1068
|
+
if (dedupe && candidates.length > 1) {
|
|
1069
|
+
deduped = [];
|
|
1070
|
+
const buckets = new Map();
|
|
1071
|
+
const undated = new Map();
|
|
1072
|
+
const allDates = new Map();
|
|
1073
|
+
const span = 7 * DAY_MS;
|
|
1074
|
+
// Rare grams first. A Jaccard match at 0.75 must share a token in
|
|
1075
|
+
// both prefixes of length |grams| - ceil(0.75 * |grams|) + 1.
|
|
1076
|
+
const counts = new Map();
|
|
1077
|
+
for (const { feat } of candidates) for (const gram of feat.dedupBigrams) counts.set(gram, (counts.get(gram) ?? 0) + 1);
|
|
1078
|
+
const index = (lookup, grams, id) => {
|
|
1079
|
+
for (const gram of grams) {
|
|
1080
|
+
let posting = lookup.get(gram);
|
|
1081
|
+
if (!posting) lookup.set(gram, posting = []);
|
|
1082
|
+
posting.push(id);
|
|
1083
|
+
}
|
|
1084
|
+
};
|
|
1085
|
+
for (const cand of candidates) {
|
|
1086
|
+
const { dedupKey, dedupBigrams: grams, itemEpoch, sourceId } = cand.feat;
|
|
1087
|
+
const week = itemEpoch == null ? null : Math.floor(itemEpoch / span);
|
|
1088
|
+
const prefix = [...grams].sort((a, b) => counts.get(a) - counts.get(b) || (a < b ? -1 : a > b ? 1 : 0))
|
|
1089
|
+
.slice(0, grams.size - Math.ceil(0.75 * grams.size) + 1);
|
|
1090
|
+
let match = Infinity;
|
|
1091
|
+
if (dedupKey.length >= 6) {
|
|
1092
|
+
const checked = new Set();
|
|
1093
|
+
const tables = week === null ? [allDates] : [undated, buckets.get(week - 1), buckets.get(week), buckets.get(week + 1)];
|
|
1094
|
+
for (const table of tables) if (table) {
|
|
1095
|
+
for (const gram of prefix) for (const id of table.get(gram) ?? []) {
|
|
1096
|
+
if (id >= match || checked.has(id)) continue;
|
|
1097
|
+
checked.add(id);
|
|
1098
|
+
const feat = deduped[id].feat;
|
|
1099
|
+
if (feat.sourceId === sourceId) continue;
|
|
1100
|
+
if (itemEpoch != null && feat.itemEpoch != null && Math.abs(itemEpoch - feat.itemEpoch) > span) continue;
|
|
1101
|
+
if (jaccardSet(grams, feat.dedupBigrams) >= 0.75) match = id;
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
if (match !== Infinity) {
|
|
1106
|
+
const kept = deduped[match];
|
|
1107
|
+
const label = cand.sourceMeta?.label ?? sourceId;
|
|
1108
|
+
if (label && !kept.alsoIn.includes(label)) kept.alsoIn.push(label);
|
|
1109
|
+
} else {
|
|
1110
|
+
const id = deduped.length;
|
|
1111
|
+
deduped.push(cand);
|
|
1112
|
+
index(allDates, prefix, id);
|
|
1113
|
+
if (week === null) index(undated, prefix, id);
|
|
1114
|
+
else {
|
|
1115
|
+
let bucket = buckets.get(week);
|
|
1116
|
+
if (!bucket) buckets.set(week, bucket = new Map());
|
|
1117
|
+
index(bucket, prefix, id);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
// Stage 3: MMR + Sliding-Window Diversity Re-ranking
|
|
1124
|
+
const selected = [];
|
|
1125
|
+
const remaining = [...deduped];
|
|
1126
|
+
const lambda = 0.78;
|
|
1127
|
+
const mmrWindow = Math.min(remaining.length, 60);
|
|
1128
|
+
const similarities = [];
|
|
1129
|
+
for (let i = 0; i < remaining.length; i++) remaining[i].rankIndex = i;
|
|
1130
|
+
|
|
1131
|
+
while (remaining.length > 0 && selected.length < mmrWindow) {
|
|
1132
|
+
let bestIdx = 0;
|
|
1133
|
+
let bestMmr = -Infinity;
|
|
1134
|
+
const prev = selected[selected.length - 1];
|
|
1135
|
+
const sourceCounts = new Map();
|
|
1136
|
+
for (let i = Math.max(0, selected.length - 6); i < selected.length; i++) {
|
|
1137
|
+
const id = selected[i].feat.sourceId;
|
|
1138
|
+
sourceCounts.set(id, (sourceCounts.get(id) ?? 0) + 1);
|
|
1139
|
+
}
|
|
1140
|
+
let latest;
|
|
1141
|
+
if (prev) {
|
|
1142
|
+
const slot = (selected.length - 1) % 6;
|
|
1143
|
+
latest = similarities[slot] ??= new Float64Array(deduped.length);
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
for (let i = 0; i < remaining.length; i += 1) {
|
|
1147
|
+
const cand = remaining[i];
|
|
1148
|
+
const isPast = cand.feat.kind === 'event' && cand.item.past;
|
|
1149
|
+
let maxSim = 0;
|
|
1150
|
+
if (latest) latest[cand.rankIndex] = jaccardSet(cand.feat.tokenSet, prev.feat.tokenSet);
|
|
1151
|
+
for (const scores of similarities) maxSim = Math.max(maxSim, scores[cand.rankIndex]);
|
|
1152
|
+
|
|
1153
|
+
let streakPenalty = 0;
|
|
1154
|
+
if (!isPast) {
|
|
1155
|
+
if (prev && prev.feat.sourceId === cand.feat.sourceId) {
|
|
1156
|
+
streakPenalty += 0.18;
|
|
1157
|
+
}
|
|
1158
|
+
const sameSourceCount = sourceCounts.get(cand.feat.sourceId) ?? 0;
|
|
1159
|
+
if (sameSourceCount >= 2) {
|
|
1160
|
+
streakPenalty += 0.22 * (sameSourceCount - 1);
|
|
1161
|
+
}
|
|
1162
|
+
const primaryTopic = cand.feat.topics[0];
|
|
1163
|
+
if (primaryTopic && prev && prev.feat.topics[0] === primaryTopic) {
|
|
1164
|
+
streakPenalty += 0.08;
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
const mmrScore = lambda * cand.rawScore - (1 - lambda) * maxSim - streakPenalty;
|
|
1169
|
+
if (mmrScore > bestMmr) {
|
|
1170
|
+
bestMmr = mmrScore;
|
|
1171
|
+
bestIdx = i;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
selected.push(remaining.splice(bestIdx, 1)[0]);
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
if (remaining.length > 0) selected.push(...remaining);
|
|
1179
|
+
|
|
1180
|
+
// Guarantee at least 1 exploration item inside top-8 when available and non-past
|
|
1181
|
+
if (selected.length >= 6 && state.stats.totalImpressions >= 4) {
|
|
1182
|
+
const hasExplorationInTop = selected.slice(0, 8).some((c) => c.channels.includes('exploration'));
|
|
1183
|
+
if (!hasExplorationInTop) {
|
|
1184
|
+
const expIdx = selected.findIndex(
|
|
1185
|
+
(c, idx) => idx >= 8 && c.channels.includes('exploration') && !(c.feat.kind === 'event' && c.item.past)
|
|
1186
|
+
);
|
|
1187
|
+
if (expIdx !== -1) {
|
|
1188
|
+
const [expItem] = selected.splice(expIdx, 1);
|
|
1189
|
+
selected.splice(Math.min(5, selected.length), 0, expItem);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
// Stage 4: Attach explainable reasons and normalized scores (0..100)
|
|
1195
|
+
const maxRaw = selected.reduce((m, c) => Math.max(m, c.rawScore), 0.1);
|
|
1196
|
+
const minRaw = selected.reduce((m, c) => Math.min(m, c.rawScore), 0);
|
|
1197
|
+
const span = Math.max(0.25, maxRaw - minRaw);
|
|
1198
|
+
|
|
1199
|
+
return selected.map((entry) => {
|
|
1200
|
+
const normalizedScore = Math.round(clamp(((entry.rawScore - minRaw) / span) * 100, 0, 100));
|
|
1201
|
+
const reason = buildExplainableReason(entry, agendaInfo, nowMs);
|
|
1202
|
+
return {
|
|
1203
|
+
...entry.item,
|
|
1204
|
+
reason,
|
|
1205
|
+
score: normalizedScore,
|
|
1206
|
+
topics: entry.feat.topics,
|
|
1207
|
+
channels: entry.channels,
|
|
1208
|
+
alsoIn: entry.alsoIn
|
|
1209
|
+
};
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
function buildExplainableReason(entry, agendaInfo, nowMs) {
|
|
1214
|
+
const { item, feat, meta, sourceMeta, channels } = entry;
|
|
1215
|
+
const reasons = [];
|
|
1216
|
+
|
|
1217
|
+
if (meta.explicitHits.length > 0) {
|
|
1218
|
+
reasons.push(`兴趣匹配:${meta.explicitHits.join('、')}`);
|
|
1219
|
+
} else if (meta.matchedUserTerms.length > 0 && (meta.shortHits > 0 || meta.longHits > 0)) {
|
|
1220
|
+
reasons.push(`常看相关:${meta.matchedUserTerms.slice(0, 2).join('、')}`);
|
|
1221
|
+
} else if (channels.includes('course_context')) {
|
|
1222
|
+
reasons.push('与你的课表方向相关');
|
|
1223
|
+
} else if (channels.includes('favorite_source') && sourceMeta?.label) {
|
|
1224
|
+
reasons.push(`你常看「${sourceMeta.label}」`);
|
|
1225
|
+
} else if (channels.includes('exploration') && sourceMeta?.label && state.stats.totalImpressions >= 4) {
|
|
1226
|
+
reasons.push(`为你探索「${sourceMeta.label}」`);
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
if (feat.urgency >= 0.7 && feat.kind !== 'event') {
|
|
1230
|
+
reasons.push('近期重要通知');
|
|
1231
|
+
}
|
|
1232
|
+
if (item.source === 'youth-enrolling') {
|
|
1233
|
+
reasons.push(item.enrollmentRatio ? `二课报名中(${item.enrollmentRatio})` : '二课报名中');
|
|
1234
|
+
} else if (item.requiresRegistration && item.intent === 'activity') {
|
|
1235
|
+
reasons.push('需报名');
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
if (feat.kind === 'notice') {
|
|
1239
|
+
reasons.push('学校通知');
|
|
1240
|
+
} else if (feat.kind === 'news') {
|
|
1241
|
+
reasons.push('校园新闻');
|
|
1242
|
+
} else if (item.past) {
|
|
1243
|
+
reasons.push('已结束');
|
|
1244
|
+
} else if (item.start != null) {
|
|
1245
|
+
reasons.push(item.start > nowMs ? '未开始' : '进行中');
|
|
1246
|
+
if (item.secondClassroom) reasons.push('计入二课');
|
|
1247
|
+
if (agendaInfo?.overlaps?.(item)) {
|
|
1248
|
+
reasons.push('与已导入日程冲突');
|
|
1249
|
+
} else if (agendaInfo?.covered?.(item)) {
|
|
1250
|
+
reasons.push('与已导入日程不冲突');
|
|
1251
|
+
} else {
|
|
1252
|
+
reasons.push('本地日程未完整覆盖该时段,是否冲突待核对');
|
|
1253
|
+
}
|
|
1254
|
+
} else {
|
|
1255
|
+
reasons.push(item.date ? '具体时间待公布' : '时间待公布');
|
|
1256
|
+
if (agendaInfo?.hasAgenda) reasons.push('是否冲突待核对');
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
if (entry.alsoIn.length > 0) {
|
|
1260
|
+
reasons.push(`同步见于:${entry.alsoIn.slice(0, 2).join('、')}`);
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
return reasons.join(';');
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
function getProfile() {
|
|
1267
|
+
const nowMs = now();
|
|
1268
|
+
const topTerms = (map, halfLifeMs, limit) => Object.entries(map)
|
|
1269
|
+
.map(([term, rec]) => ({
|
|
1270
|
+
term,
|
|
1271
|
+
weight: Number((rec.weight * decayFactor(nowMs - (rec.updatedAt ?? nowMs), halfLifeMs)).toFixed(3))
|
|
1272
|
+
}))
|
|
1273
|
+
.filter((x) => x.weight > 0.15)
|
|
1274
|
+
.sort((a, b) => b.weight - a.weight)
|
|
1275
|
+
.slice(0, limit);
|
|
1276
|
+
|
|
1277
|
+
const topSources = Object.entries(state.sources)
|
|
1278
|
+
.map(([source, stat]) => ({
|
|
1279
|
+
source,
|
|
1280
|
+
ctr: Number(bayesianCtr(stat).toFixed(3)),
|
|
1281
|
+
impressions: stat.impressions,
|
|
1282
|
+
positive: Number(stat.positive.toFixed(2))
|
|
1283
|
+
}))
|
|
1284
|
+
.sort((a, b) => b.ctr - a.ctr || b.positive - a.positive)
|
|
1285
|
+
.slice(0, 10);
|
|
1286
|
+
|
|
1287
|
+
const topTopics = Object.entries(state.topics)
|
|
1288
|
+
.map(([topic, stat]) => ({
|
|
1289
|
+
topic,
|
|
1290
|
+
label: TOPIC_TAXONOMY[topic]?.label ?? topic,
|
|
1291
|
+
affinity: Number(bayesianCtr(stat).toFixed(3)),
|
|
1292
|
+
impressions: stat.impressions,
|
|
1293
|
+
positive: Number(stat.positive.toFixed(2))
|
|
1294
|
+
}))
|
|
1295
|
+
.sort((a, b) => b.affinity - a.affinity || b.positive - a.positive)
|
|
1296
|
+
.slice(0, 8);
|
|
1297
|
+
|
|
1298
|
+
const dislikedCount = Object.values(state.items).filter((r) => r.disliked).length;
|
|
1299
|
+
|
|
1300
|
+
return {
|
|
1301
|
+
shortTermInterests: topTerms(state.shortTermTerms, SHORT_HALF_LIFE_MS, 12),
|
|
1302
|
+
longTermInterests: topTerms(state.longTermTerms, LONG_HALF_LIFE_MS, 15),
|
|
1303
|
+
pinnedInterests: [...state.pinnedInterests],
|
|
1304
|
+
topSources,
|
|
1305
|
+
topTopics,
|
|
1306
|
+
mutedSources: [...state.mutedSources],
|
|
1307
|
+
mutedTopics: [...state.mutedTopics],
|
|
1308
|
+
dislikedCount,
|
|
1309
|
+
weights: { ...state.weights },
|
|
1310
|
+
stats: { ...state.stats }
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
return {
|
|
1315
|
+
rank,
|
|
1316
|
+
recordFeedback,
|
|
1317
|
+
getProfile
|
|
1318
|
+
};
|
|
1319
|
+
}
|