-
Notifications
You must be signed in to change notification settings - Fork 1
/
RippleGPT.js
328 lines (287 loc) · 9.63 KB
/
RippleGPT.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
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
/*
Name: RippleAi
Author: Ripple
Author URI: https://hiripple.com/
Version: 1.0.0
License: GNU General Public License v3.0
License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/
const RippleGPT = {
getTitleAndContent: function () {
const title = document.title;
const container = document.querySelector(RippleGPT_postSelector);
const paragraphs = container.querySelectorAll('p');
const headings = container.querySelectorAll('h1, h2, h3, h4, h5');
let content = '';
for (let h of headings) {
content += h.innerText + ' ';
}
for (let p of paragraphs) {
const filteredText = p.innerText.replace(/https?:\/\/[^\s]+/g, '');
content += filteredText;
}
const combinedText = title + ' ' + content;
const truncatedText = combinedText.slice(0, 3000);
return truncatedText;
},
fetchRippleGPT: async function(content) {
const apiUrl = GPT_URL + 'api/aisummary';
const timeout = 500000;
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ content: content }),
signal: controller.signal,
});
if (response.ok) {
const data = await response.json();
const summary = data.summary.content;
return summary;
} else {
throw new Error('请求失败');
}
} catch (error) {
if (error.name === 'AbortError') {
console.error('请求超时');
} else {
console.error('请求失败:', error);
}
return '获取文章摘要超时。';
}
},
};
async function fetchAudio(text) {
const result = processText(text);
const url = VITS_URL;
const data = {
text: result.processedText,
language: result.language,
speed: 0.8,
noise_scale: 0.2,
noise_scale_w: 0.668
};
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
if (response.ok) {
const audioData = await response.json();
return audioData.url;
} else {
throw new Error("请求失败");
}
} catch (error) {
console.error("请求失败:", error);
}
}
function isChinese(char) {
const charCode = char.charCodeAt(0);
return (charCode >= 0x4E00 && charCode <= 0x9FFF) || (charCode >= 0x3000 && charCode <= 0x303F);
}
function processText(text) {
let processedText = "";
let prevCharType = null;
let language;
let isChineseDetected = false;
let isEnglishDetected = false;
for (const char of text) {
const isCharChinese = isChinese(char) || /[\u3000-\u303F\uFF00-\uFFEF]/.test(char);
if (isCharChinese) {
isChineseDetected = true;
if (prevCharType !== "zh") {
if (prevCharType === "en") {
processedText += "[EN]";
}
processedText += "[ZH]";
prevCharType = "zh";
}
} else {
isEnglishDetected = true;
if (prevCharType !== "en") {
if (prevCharType === "zh") {
processedText += "[ZH]";
}
processedText += "[EN]";
prevCharType = "en";
}
}
processedText += char;
}
if (isChineseDetected && isEnglishDetected) {
if (prevCharType === "zh") {
processedText += "[ZH]";
} else if (prevCharType === "en") {
processedText += "[EN]";
}
language = "Mix";
} else if (isChineseDetected) {
processedText = text;
language = "简体中文";
} else {
processedText = text;
language = "English";
}
return { processedText, language };
}
async function fetchAudioAndPlay() {
const cyberContainer = document.getElementById("cyber-container");
cyberContainer.onclick = null; // 取消容器的点击属性
const aiSummaryTarget = document.querySelector(".ai-summary-target");
const cyberText = document.querySelector(".cyber-text");
const preparingText = document.createElement("span");
preparingText.innerText = "准备中...";
preparingText.classList.add("blinking");
cyberText.innerHTML = ""; // 先清空原来的文字
cyberText.appendChild(preparingText);
// 获取音频链接
const audioUrl = await fetchAudio(aiSummaryTarget.innerText);
// 使用系统默认音频播放器
const audioElement = document.createElement("audio");
audioElement.src = audioUrl;
audioElement.controls = true;
audioElement.style.height = "30px";
audioElement.style.width = "50%";
cyberText.removeChild(preparingText); // 移除 "准备中..." 文字
// 将音频元素插入到 cyberText 元素
cyberText.appendChild(audioElement);
}
function runRippleGPT() {
const rippleAiDiv = document.querySelector('.ripple-ai.mt-4');
rippleAiDiv.innerHTML = `
<div class="ripple-ai-header flex items-center">
<a href="https://github.com/CelestialRipple/AI-Summary" target="_blank">
<img src="https://myripple.cc/uploads/2023/04/1681875518-icon-RippleGPT.png" class="ai-icon">
</a>
<span class="Aisummary"> AI 生成的摘要</span>
<button class="ripple-ai-btn">AI 插图</button>
</div>
<p class="ripple-ai-content ai-summary-target"></p>
<div class="powered-by">powered by RippleAi</div>
`;
const cyberContainerHtml = `
<div id="cyber-container" class="cyber-container" onclick="fetchAudioAndPlay()" style="cursor: pointer;"><div class="cyber-banner-short bg-purple fg-white mt-4"><span class="cyber-text">让大名鼎鼎的V为您介绍!</span>
</div> <div class="image-container" style="z-index: 1;margin-left: -60px;">
<img src="https://myripple.cc/uploads/2023/04/1681997903-V-removebg-preview-2.png" style="max-height: 60px; max-width: 60px;">
</div></div>
`;
const content = RippleGPT.getTitleAndContent();
const aiSummaryTarget = document.querySelector('.ai-summary-target');
const aiButton = document.querySelector('.ripple-ai-btn');
// 设置按钮为不可见
aiButton.style.display = 'none';
// 创建“生成中”提示的容器
const aiExplanationDiv = document.createElement('div');
aiExplanationDiv.className = 'RippleGPT-explanation';
aiSummaryTarget.appendChild(aiExplanationDiv);
const aiIcon = document.querySelector('.ai-icon');
aiIcon.classList.add('rotating');
// 给“生成中”提示添加 TypeIt 打字效果
new TypeIt(aiExplanationDiv, {
strings: ['RippleGPT生成中...'],
speed: 70,
loop: true,
waitUntilVisible: true,
}).go();
RippleGPT.fetchRippleGPT(content).then(summary => {
aiSummaryTarget.removeChild(aiExplanationDiv);
new TypeIt(aiSummaryTarget, {
strings: [summary],
speed: 50,
loop: false,
waitUntilVisible: true,
}).go();
setTimeout(() => {
aiButton.style.display = 'inline-block';
aiIcon.classList.remove('rotating');
// 将新的 HTML 块插入到页面中
const cyberContainerDiv = document.createElement('div');
cyberContainerDiv.innerHTML = cyberContainerHtml;
rippleAiDiv.appendChild(cyberContainerDiv);
// 添加从左侧淡入的动画
setTimeout(() => {
const cyberContainer = cyberContainerDiv.querySelector('.cyber-container');
cyberContainer.classList.add('fade-in-animation');
}, 500);
}, summary.length * 60);
aiButton.addEventListener('click', () => {
aiButton.disabled = true;
aiButton.innerHTML = 'Prompt生成中';
aiButton.classList.add('blinking');
aiButton.style.display = 'inline-block';
aiIcon.classList.remove('rotating');
const promptContent = aiSummaryTarget.innerText;
fetch(GPT_URL + 'api/aiprompt', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ content: promptContent }),
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败');
}
})
.then(data => {
aiButton.innerHTML = 'Mj绘制中';
return fetch(MJ_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt: data.summary.content }),
});
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('请求失败');
}
})
.then(data => {
if (data.error) {
alert('Error: ' + data.error);
aiButton.style.display = 'inline-block';
aiIcon.classList.remove('rotating');
aiButton.innerHTML = 'AI 插图';
aiButton.classList.remove('blinking');
aiButton.disabled = false;
return;
}
const imgSrc = MJ_URL + data.latest_image_url;
const imgDiv = document.createElement('div');
imgDiv.className = 'wp-block-image';
const imgLink = document.createElement('a');
imgLink.href = imgSrc;
imgLink.setAttribute('data-fancybox', 'gallery');
const img = document.createElement('img');
img.src = imgSrc;
imgLink.appendChild(img);
imgDiv.appendChild(imgLink);
aiSummaryTarget.parentElement.insertBefore(imgDiv, aiSummaryTarget);
setTimeout(() => {
aiButton.style.display = 'inline-block';
aiButton.innerHTML = 'AI 插图';
aiButton.classList.remove('blinking');
aiButton.disabled = false;
aiIcon.classList.remove('rotating');
}, 2000);
})
.catch(error => {
console.error('请求失败:', error);
});
});
});}