-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
272 lines (238 loc) · 8.82 KB
/
Copy pathbackground.js
File metadata and controls
272 lines (238 loc) · 8.82 KB
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
const DEFAULT_SETTINGS = {
baseUrl: "https://api.openai.com/v1",
apiKey: "",
model: "gpt-4o-mini",
temperature: 0.2,
maxViewpoints: 5,
minRawCommentsThreshold: 10,
v2exApiBaseUrl: "https://www.v2ex.com/api"
};
const TOPIC_CACHE_TTL_MS = 10 * 60 * 1000;
const topicCache = new Map();
function normalizeBaseUrl(baseUrl) {
return (baseUrl || "").replace(/\/$/, "");
}
async function getSettings() {
const saved = await chrome.storage.sync.get(DEFAULT_SETTINGS);
return {
...DEFAULT_SETTINGS,
...saved,
temperature: Number(saved.temperature ?? DEFAULT_SETTINGS.temperature),
maxViewpoints: Number(saved.maxViewpoints ?? DEFAULT_SETTINGS.maxViewpoints),
minRawCommentsThreshold: Number(
saved.minRawCommentsThreshold ?? DEFAULT_SETTINGS.minRawCommentsThreshold
)
};
}
function buildRateLimitInfo(response) {
const limit = Number(response.headers.get("X-Rate-Limit-Limit") || 0);
const remaining = Number(response.headers.get("X-Rate-Limit-Remaining") || 0);
const reset = Number(response.headers.get("X-Rate-Limit-Reset") || 0);
return {
limit: Number.isFinite(limit) ? limit : 0,
remaining: Number.isFinite(remaining) ? remaining : 0,
reset: Number.isFinite(reset) ? reset : 0
};
}
async function fetchJsonWithRateInfo(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`请求失败(${response.status}): ${url}`);
}
return {
data: await response.json(),
rateInfo: buildRateLimitInfo(response)
};
}
function getCacheKey(topicId, apiBase) {
return `${apiBase}::${topicId}`;
}
async function fetchV2EXTopicAndReplies(topicId, v2exApiBaseUrl) {
const apiBase = normalizeBaseUrl(v2exApiBaseUrl || DEFAULT_SETTINGS.v2exApiBaseUrl);
const cacheKey = getCacheKey(topicId, apiBase);
const now = Date.now();
const cached = topicCache.get(cacheKey);
if (cached && now - cached.at < TOPIC_CACHE_TTL_MS) {
return {
...cached.value,
apiMeta: { ...cached.value.apiMeta, cached: true }
};
}
const topicUrl = `${apiBase}/topics/show.json?id=${encodeURIComponent(topicId)}`;
const repliesUrl = `${apiBase}/replies/show.json?topic_id=${encodeURIComponent(topicId)}`;
const [{ data: topicJson, rateInfo: topicRateInfo }, { data: repliesJson, rateInfo: repliesRateInfo }] =
await Promise.all([fetchJsonWithRateInfo(topicUrl), fetchJsonWithRateInfo(repliesUrl)]);
const topic = Array.isArray(topicJson) ? topicJson[0] : null;
if (!topic) {
throw new Error("未获取到帖子内容,请检查 topic id 是否正确。");
}
const result = {
title: String(topic.title || ""),
topicContent: String(topic.content || topic.content_rendered || ""),
rawCommentCount: Array.isArray(repliesJson) ? repliesJson.length : 0,
comments: Array.isArray(repliesJson)
? repliesJson
.map((item) => String(item?.content || item?.content_rendered || "").replace(/\s+/g, " ").trim())
.filter(Boolean)
: [],
apiMeta: {
cached: false,
topicRateInfo,
repliesRateInfo
}
};
topicCache.set(cacheKey, { at: now, value: result });
return result;
}
function buildPrompt({ title, topicContent, comments, maxViewpoints }) {
const commentsText = comments.map((text, index) => `${index + 1}. ${text}`).join("\n");
return [
"你是一个评论观点分析助手。",
"请结合主贴问题和评论内容,提取主要观点分布。",
"输出必须是 JSON,不要包含 markdown 代码块。",
`最多输出 ${maxViewpoints} 个观点。`,
"JSON 结构如下:",
'{"viewpoints":[{"label":"观点","count":12}],"totalComments":100,"summary":"一句话总结"}',
"要求:",
"1. label 要简洁(不超过 18 个字);",
"2. count 为该观点对应评论数量;",
"3. totalComments 为参与分类的评论总数;",
"4. 忽略无关、灌水评论;",
"5. 如果评论不足,viewpoints 可以为空数组;",
"6. 如果帖子标题明显是一个提问,则 label 应该是该问题的具体答案(如品牌名、产品名、方案名等),而非笼统的观点描述。例如标题问“智驾谁是第一”,label 应为“小鹏”、“华为”等具体回答。",
"",
`帖子标题:${title || "(无标题)"}`,
`主贴内容:${topicContent || "(无正文)"}`,
"评论列表:",
commentsText || "(无评论)"
].join("\n");
}
function parseJsonFromModel(content) {
if (!content) {
throw new Error("模型返回为空。");
}
const trimmed = content.trim();
try {
return JSON.parse(trimmed);
} catch (_error) {
const match = trimmed.match(/\{[\s\S]*\}/);
if (!match) {
throw new Error("模型返回不是有效 JSON。");
}
return JSON.parse(match[0]);
}
}
function sanitizeResult(raw, commentCount, maxViewpoints) {
const viewpoints = Array.isArray(raw?.viewpoints) ? raw.viewpoints : [];
const limited = viewpoints
.map((item) => ({
label: String(item?.label || "未命名观点").slice(0, 30),
count: Math.max(0, Number(item?.count) || 0)
}))
.filter((item) => item.label && item.count > 0)
.slice(0, maxViewpoints);
const totalRawCount = limited.reduce((sum, item) => sum + item.count, 0);
if (commentCount > 0 && totalRawCount > commentCount) {
const ratio = commentCount / totalRawCount;
const scaled = limited.map((item) => {
const exact = item.count * ratio;
return {
...item,
count: Math.floor(exact),
fraction: exact - Math.floor(exact)
};
});
let remainder = commentCount - scaled.reduce((sum, item) => sum + item.count, 0);
scaled
.slice()
.sort((a, b) => b.fraction - a.fraction)
.forEach((item) => {
if (remainder <= 0) {
return;
}
item.count += 1;
remainder -= 1;
});
scaled.forEach((item, index) => {
limited[index].count = item.count;
});
}
const totalFromViewpoints = limited.reduce((sum, item) => sum + item.count, 0);
const totalComments = Math.min(
Math.max(Number(raw?.totalComments) || totalFromViewpoints, totalFromViewpoints),
Math.max(commentCount, totalFromViewpoints)
);
limited.sort((a, b) => b.count - a.count);
return {
viewpoints: limited,
totalComments,
summary: String(raw?.summary || "")
};
}
async function analyzeDistribution(payload) {
const settings = await getSettings();
if (!settings.apiKey) {
throw new Error("请先在扩展设置中填写 OpenAI API Key。");
}
const topicData = await fetchV2EXTopicAndReplies(payload.topicId, settings.v2exApiBaseUrl);
const pageComments = Array.isArray(payload?.pageComments)
? payload.pageComments.map((item) => String(item || "").replace(/\s+/g, " ").trim()).filter(Boolean)
: [];
const comments = topicData.comments.length ? topicData.comments : pageComments;
if (!comments.length) {
return {
viewpoints: [],
totalComments: 0,
summary: "该帖子暂无评论。",
apiMeta: topicData.apiMeta
};
}
const minRawCommentsThreshold = Math.max(0, Math.floor(settings.minRawCommentsThreshold || 0));
if (comments.length <= minRawCommentsThreshold) {
return {
viewpoints: [],
totalComments: comments.length,
summary: `原始评论数量小于等于 ${minRawCommentsThreshold} 条,已跳过分析。`,
apiMeta: topicData.apiMeta
};
}
const maxViewpoints = Math.max(1, Math.min(12, settings.maxViewpoints));
const requestBody = {
model: settings.model,
temperature: settings.temperature,
response_format: { type: "json_object" },
messages: [
{ role: "system", content: "你擅长总结社区讨论中的观点分布。" },
{ role: "user", content: buildPrompt({ ...topicData, comments, maxViewpoints }) }
]
};
const endpoint = `${normalizeBaseUrl(settings.baseUrl || DEFAULT_SETTINGS.baseUrl)}/chat/completions`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${settings.apiKey}`
},
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errText = await response.text();
throw new Error(`调用模型失败(${response.status}):${errText.slice(0, 300)}`);
}
const data = await response.json();
const content = data?.choices?.[0]?.message?.content;
const parsed = parseJsonFromModel(content);
return {
...sanitizeResult(parsed, comments.length, maxViewpoints),
apiMeta: topicData.apiMeta
};
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type !== "ANALYZE_V2EX_DISTRIBUTION") {
return false;
}
analyzeDistribution(message.payload)
.then((result) => sendResponse({ ok: true, result }))
.catch((error) => sendResponse({ ok: false, error: error.message || String(error) }));
return true;
});