- 注册
- 2024/07/26
- 消息
- 732
先上效果
基于佬的 分享一个好玩的油猴脚本 - 资源荟萃 - LINUX DO 并用AI修改而来
需要基于另外的油猴脚本来重定向百度的真实链接(不是我自己的脚本)
AC-baidu-重定向优化百度搜狗谷歌必应搜索_favicon_双列
需要在上面 配置项 | AC-重定向设置 里面打开这个
用AI修改了几点:
- 循环3次获取上面脚本解析出来的真实地址
- 总结展示的样式
- 提示词(没错,提示词也是AI生成的)
下面上脚本
// ==UserScript==
// @name 百度搜索总结 via Gemini AI
// @description Baidu Search with AI-Generated Annotation via Gemini
// @version 0.99
// @license MIT
// @namespace mainfunc
// @match https://www.baidu.com/s*
// @run-at document-end
// @grant GM.setValue
// @grant GM.getValue
// ==/UserScript==
(async () => {
// await GM.setValue("GEMINI_API_KEY", "");
let GEMINI_API_KEY = await GM.getValue("GEMINI_API_KEY");
if (!GEMINI_API_KEY || !Object.keys(GEMINI_API_KEY).length) {
GEMINI_API_KEY = window.prompt('请从 Google AI Studio 获取 API key\nhttps://ai.google.dev/aistudio', '');
await GM.setValue("GEMINI_API_KEY", GEMINI_API_KEY);
}
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=${GEMINI_API_KEY}`;
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// 获取真实URL的函数
const getRealUrl = async (baiduUrl, maxAttempts = 3) => {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (!baiduUrl.startsWith('https://www.baidu.com/link?url=')) {
return baiduUrl;
}
await delay(1000); // 等待1秒
console.log(`Attempting to get real URL, attempt ${attempt + 1}`);
}
return null; // 三次尝试后仍然是百度链接格式则返回null
};
// ########## Results ##########
const processArticle = async (article, title, url) => {
try {
document.querySelector('#gemini-ticker').style.opacity = '1';
// 获取真实URL
const realUrl = await getRealUrl(url);
// 创建或获取摘要容器
let summaryContainer = article.querySelector('.gemini-summary');
if (!summaryContainer) {
summaryContainer = document.createElement('div');
summaryContainer.className = 'gemini-summary';
summaryContainer.style.marginTop = '10px';
summaryContainer.style.padding = '10px';
summaryContainer.style.borderLeft = '3px solid #ffbf00';
summaryContainer.style.backgroundColor = '#f8f9fa';
article.appendChild(summaryContainer);
}
if (!realUrl) {
summaryContainer.textContent = '✦ 未解析到真实链接~';
article.classList.add('gemini-annotated');
return;
}
const searchQuery = document.querySelector('#kw').value;
const promptText =
`我正在搜索关于 ${searchQuery} 的内容。
请按照以下执行流程完成操作:
1. 访问指定 URL 以获取网页信息。若 URL 无法访问,则输出"无法访问,进去吧你~"。
4. 如果能成功访问,请以猫娘风格、使用中文撰写大约 200 字的总结:
- 在开头分析出这个咨询的发布时间以及距现在多少时间,比如距现在X年X月X天了,不需要提示今天的日期,现在是${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(new Date().getDate()).padStart(2, '0')}
- 重点提炼网页内容的关键信息及与搜索主题 (${searchQuery}) 的关联;
- 确保信息的准确性,突出对我可能有帮助或可操作的要点;
- 风格可活泼可爱,但需包含可靠的资讯,避免空洞或夸大的描述。
5. 只输出完成的总结(或无法访问的提示),不包括额外解释。
${title} 的 URL: ${realUrl}`;
const response = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{
parts: [{
text: promptText
}],
}]
}),
});
if (!response.ok) throw new Error('Network response was not ok');
const reader = response.body.getReader();
let result = '', done = false, decoder = new TextDecoder();
while (!done) {
const { value, done: doneReading } = await reader.read();
done = doneReading;
if (value) result += decoder.decode(value, { stream: true });
}
result += decoder.decode();
const data = JSON.parse(result);
let summary = (data.candidates[0]?.content?.parts[0]?.text || '').replace(/\*\*/g, '').replace(/##/g, '');
console.log(`summary: ${summary}`);
// 动画显示摘要
let displayText = '✦ ';
const chunkSize = 20;
summaryContainer.textContent = displayText;
for (let i = 0; i < summary.length; i += chunkSize) {
const chunk = summary.slice(i, i + chunkSize);
const chunkSpan = document.createElement('span');
chunkSpan.style.opacity = '0';
chunkSpan.style.color = '#666';
chunkSpan.textContent = chunk;
summaryContainer.appendChild(chunkSpan);
await delay(100);
chunkSpan.style.transition = 'opacity 1s ease-in-out';
chunkSpan.style.opacity = '1';
}
article.classList.add('gemini-annotated');
} catch (error) {
document.querySelector('#gemini-ticker').style.opacity = '0';
await delay(5000);
console.error('Error:', error);
}
};
const throttledProcessArticle = async (article, title, url, interval) => {
await delay(interval);
return processArticle(article, title, url);
};
// ########## Ticker ##########
const insertTickerElement = () => {
const ticker = document.createElement('div');
ticker.id = 'gemini-ticker';
ticker.style.position = 'fixed';
ticker.style.right = '20px';
ticker.style.bottom = '10px';
ticker.style.fontSize = '1.5em';
ticker.style.color = '#77777777';
ticker.style.transition = 'opacity .3s';
ticker.style.zIndex = '100';
ticker.innerHTML = '✦';
document.body.appendChild(ticker);
};
// ########## Main ##########
await delay(1000);
insertTickerElement();
for (let j = 0; j < 30; j++) {
console.log(`######## attempt: ${j + 1} ########`)
// 适配百度搜索结果的选择器
const articles = Array.from(document.querySelectorAll('.result.c-container:not(.gemini-annotated)'));
if (articles.length == 0) break;
const promises = articles.map((result, i) => {
if (!result) return Promise.resolve();
const titleElement = result.querySelector('.t a, .c-title a');
if (!titleElement) return Promise.resolve();
const href = titleElement.href;
const title = titleElement.textContent;
console.log(`title: ${title}`);
console.log(`url: ${href}`);
if (!href) return Promise.resolve();
return throttledProcessArticle(result, title, href, i * 1000);
});
await Promise.all(promises);
document.querySelector('#gemini-ticker').style.opacity = '0';
}
document.querySelector('#gemini-ticker').style.opacity = '0';
})();