首页  >  文章  >  web前端  >  使用 AI/ML API、Deepgram Aura 和 IndexedDB 集成从头开始构建 Chrome 扩展

使用 AI/ML API、Deepgram Aura 和 IndexedDB 集成从头开始构建 Chrome 扩展

Linda Hamilton
Linda Hamilton原创
2024-10-26 19:52:03840浏览

介绍

构建利用人工智能技术的 Chrome 扩展程序可以通过直接向浏览器添加强大的功能来显着增强用户体验。

在本教程中,我们将介绍使用 AI/ML API、Deepgram Aura 和 IndexDB 从头开始​​构建 Chrome 扩展程序(从设置到部署)的整个过程。我们将从设置开发环境开始,包括安装必要的工具和配置我们的项目。然后,我们将深入研究 Chrome 扩展程序的核心组件:manifest.json 包含有关扩展程序的基本元数据,scripts.js 负责我们的扩展程序的行为方式,styles.css 用于添加一些样式。我们将探索如何通过 AI/ML API 将这些技术与 Deepgram Aura 集成,并使用 IndexDB 作为生成的音频文件的临时存储。在此过程中,我们将讨论构建 Chrome 扩展、处理用户查询以及在数据库中保存数据的最佳实践。学完本教程后,您将在构建 Chrome 扩展程序方面打下坚实的基础,并具备构建任何人工智能驱动的 Chrome 扩展程序的能力。

让我们简要概述一下我们将要使用的技术。

人工智能/机器学习API

AI/ML API 是一个改变游戏规则的平台,适合希望将尖端 AI 功能集成到其产品中的开发人员和 SaaS 企业家。 AI/ML API 提供对 200 多个最先进的 AI 模型的单点访问,涵盖从 NLP 到计算机视觉的所有内容。

面向开发者的主要功能:

  • 丰富的模型库:200 个预训练模型,用于快速原型设计和部署
  • 自定义选项:微调模型以适合您的特定用例
  • 开发人员友好的集成:RESTful API 和 SDK,可无缝合并到您的堆栈中
  • 无服务器架构:专注于编码,而不是基础设施管理

深入研究 AI/ML API 文档; https://docs.aimlapi.com/

Chrome 扩展程序

Chrome 扩展程序是一个小型软件程序,可修改或增强 Google Chrome 网络浏览器的功能。这些扩展是使用 HTML、CSS 和 JavaScript 等 Web 技术构建的,旨在服务于单一目的,使它们易于理解和使用。

浏览 Chrome 网上应用店; https://chromewebstore.google.com/

深光光环

Deepgram Aura 是第一个专为实时对话式 AI 代理和应用程序设计的文本转语音 (TTS) AI 模型。它以无与伦比的速度和效率提供类人语音质量,使其成为构建响应灵敏、高吞吐量的语音 AI 体验的游戏规则改变者。

了解更多技术细节; https://aimlapi.com/models/aura

索引数据库

IndexedDB 是一个低级 API,用于客户端存储大量结构化数据(包括文件/blob)。 IndexedDB 是一个基于 JavaScript 的面向对象数据库。

了解更多关键概念和用法; https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API

Chrome 扩展程序入门

构建 Chrome 扩展程序需要了解其结构、权限以及它如何与网页交互。我们将首先设置开发环境并创建扩展所需的基础文件。

设置您的开发环境

在我们开始编码之前,请确保您具备以下条件:

  • Chrome 浏览器:我们将在其中加载和测试扩展程序的浏览器。
  • 文本编辑器或 IDE:Visual Studio Code、Sublime Text 或 Atom 等工具适合编辑代码。我们将在本教程中使用 Visual Studio Code。
  • HTML、CSS 和 JavaScript 的基本知识:熟悉这些技术对于构建 Chrome 扩展程序至关重要。

创建项目结构

最小的 Chrome 扩展程序至少需要三个文件:

  • manifest.json:包含扩展的元数据和配置。
  • scripts.js:保存定义扩展行为的 JavaScript 代码。
  • styles.css:包括扩展的 UI 元素的任何样式。

让我们为我们的项目创建一个目录并设置这些文件。
第 1 步:创建新目录
打开终端并运行以下命令为您的扩展创建一个新文件夹:

mkdir my-first-chrome-extension
cd my-first-chrome-extension

第 2 步:创建基本文件
在新目录中,创建必要的文件:

touch manifest.json
touch scripts.js
touch styles.css

了解manifest.json

manifest.json 文件是 Chrome 扩展程序的核心。它告诉浏览器您的扩展程序、它的用途以及它需要什么权限。让我们深入研究如何正确配置此文件。

{
  "manifest_version": 3,
  "name": "Read Aloud",
  "version": "1.0",
  "description": "Read Aloud anything in any tab",
  "host_permissions": [
    "*://*.aimlapi.com/*"
],
  "permissions": [
      "activeTab"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["scripts.js"],
      "css": ["styles.css"]
    }
  ],
  "icons": {
    "16": "icons/icon.png",
    "48": "icons/icon.png",
    "128": "icons/icon.png"
  }
}

manifest.json 中的基本字段

manifest.json 必须至少包含:

  • manifest_version:指定清单文件格式的版本。 Chrome 目前使用版本 3。
  • 名称:您的扩展程序的名称,它将显示给用户。
  • 版本:扩展程序的版本号,遵循语义版本控制。

添加元数据和权限

除了必要字段之外,我们将添加:

  • 描述:您的扩展程序功能的简短摘要。
  • host_permissions:指定扩展可以访问哪些域。为了与 AI/ML API 集成,我们需要访问 *.aimlapi.com。
  • 权限:声明所需的特殊权限,例如访问活动选项卡。
  • content_scripts:定义要注入网页的脚本和样式。
  • 图标:提供各种尺寸的扩展图标。

关键字段的解释

  • manifest_version:设置为 3 以使用最新的 Chrome 扩展功能。
  • 名称:我们将我们的扩展命名为“Read Aloud”,以反映其功能。
  • 版本:以“1.0”开头表示初始版本。
  • 描述:“大声朗读任何选项卡中的任何内容”告知用户该扩展程序的用途。
  • host_permissions:通配符 *://*.aimlapi.com/* 允许扩展程序与 aimlapi.com 的任何子域进行通信,这是 API 调用所必需的。
  • 权限:“activeTab”允许扩展程序与当前选项卡的内容进行交互。
  • content_scripts:指定将scripts.js 和styles.css 注入到所有网页(“”)。
  • 图标:扩展程序的引用图标文件(确保图标目录中有适当的图标文件)。

生成图标

打开浏览器并访问 chatgpt.com。现在让我们为 Chrome 扩展程序生成图标。我们将使用一个图标来实现不同的尺寸(完全没问题)。

输入以下提示:

为我的“Read Aloud”Chrome 扩展程序生成黑白图标。此扩展允许用户突出显示网站中的特定文本并收听它。它是由人工智能驱动的 Chrome 扩展。背景应为白色且纯色。

等待几秒钟,直到 ChatGPT 生成图标(图像)。单击下载并将其重命名为 icon.png。然后放入icons文件夹内。

完成manifest.json

正确定义所有字段后,您的manifest.json将使浏览器能够理解并正确加载您的扩展。


开发 script.js

scripts.js 文件包含控制扩展行为方式的逻辑。我们将概述您的脚本需要实现的关键功能。

变量和初始化

首先设置必要的变量:

  • API 密钥:您需要来自 AI/ML API 平台的 API 密钥来验证您的请求。
  • 叠加元素:为叠加层和“朗读”按钮创建 DOM 元素。
  • 选择变量:存储有关用户选择的文本及其位置的信息。
mkdir my-first-chrome-extension
cd my-first-chrome-extension

处理文本选择

您的扩展程序应该检测用户何时选择网页上的文本:

  • 事件监听器:将 mouseup 事件监听器附加到文档以检测用户何时完成选择文本。
mkdir my-first-chrome-extension
cd my-first-chrome-extension
  • 选择检测:检查所选文本是否不为空并存储。
touch manifest.json
touch scripts.js
touch styles.css
  • 叠加层定位:计算叠加层的放置位置,使其靠近所选文本。
{
  "manifest_version": 3,
  "name": "Read Aloud",
  "version": "1.0",
  "description": "Read Aloud anything in any tab",
  "host_permissions": [
    "*://*.aimlapi.com/*"
],
  "permissions": [
      "activeTab"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["scripts.js"],
      "css": ["styles.css"]
    }
  ],
  "icons": {
    "16": "icons/icon.png",
    "48": "icons/icon.png",
    "128": "icons/icon.png"
  }
}
  • 叠加管理:确保在添加新叠加之前删除任何现有叠加。
// Set your AIML_API_KEY key
const AIML_API_KEY = ''; // Replace with your AIML_API_KEY key

// Create the overlay
const overlay = document.createElement('div');
overlay.id = 'read-aloud-overlay';

// Create the "Read Aloud" button
const askButton = document.createElement('button');
askButton.id = 'read-aloud-button';
askButton.innerText = 'Read Aloud';

// Append the button to the overlay
overlay.appendChild(askButton);

// Variables to store selected text and range
let selectedText = '';
let selectedRange = null;

完整代码:

document.addEventListener('mouseup', (event) => {
  console.log('mouseup event: ', event);
  //...code
}

与 AI/ML API 交互

当用户单击“朗读”按钮时:

  • 输入验证:检查所选文本是否满足长度要求。
const selection = window.getSelection();
const text = selection.toString().trim();
if (text !== '') {
  const range = selection.getRangeAt(0);
  const rect = range.getBoundingClientRect();
  • 禁用按钮:通过在处理过程中禁用按钮来防止多次点击。
// Set the position of the overlay
overlay.style.top = `${window.scrollY + rect.top - 50}px`; // Adjust as needed
overlay.style.left = `${window.scrollX + rect.left + rect.width / 2 - 70}px`; // Adjust to center the overlay

selectedText = text;
selectedRange = range;
  • API 请求:使用选定的文本向 AI/ML API 发送 POST 请求,以进行文本到语音转换。
// Remove existing overlay if any
const existingOverlay = document.getElementById('read-aloud-overlay');
if (existingOverlay) {
  existingOverlay.remove();
}

// Append the overlay to the document body
document.body.appendChild(overlay);
} else {
  // Remove overlay if no text is selected
  const existingOverlay = document.getElementById('read-aloud-overlay');
  if (existingOverlay) {
    existingOverlay.remove();
  }
}
  • 错误处理:优雅地处理API请求期间发生的任何错误。
// Function to handle text selection
document.addEventListener('mouseup', (event) => {
  console.log('mouseup event: ', event);
  const selection = window.getSelection();
  const text = selection.toString().trim();
  if (text !== '') {
    const range = selection.getRangeAt(0);
    const rect = range.getBoundingClientRect();

    // Set the position of the overlay
    overlay.style.top = `${window.scrollY + rect.top - 50}px`; // Adjust as needed
    overlay.style.left = `${window.scrollX + rect.left + rect.width / 2 - 70}px`; // Adjust to center the overlay

    selectedText = text;
    selectedRange = range;

    // Remove existing overlay if any
    const existingOverlay = document.getElementById('read-aloud-overlay');
    if (existingOverlay) {
      existingOverlay.remove();
    }

    // Append the overlay to the document body
    document.body.appendChild(overlay);
  } else {
    // Remove overlay if no text is selected
    const existingOverlay = document.getElementById('read-aloud-overlay');
    if (existingOverlay) {
      existingOverlay.remove();
    }
  }
});
  • 音频播放:收到音频后,将其播放给用户。
if (selectedText.length > 200) {
// ...code
}

使用 IndexedDB 进行存储

要有效管理音频文件:

  • 打开数据库:创建或打开 IndexedDB 数据库来存储音频 blob。
// Disable the button
askButton.disabled = true;
askButton.innerText = 'Loading...';
  • 保存音频:从 API 接收音频 blob 后将其存储在 IndexedDB 中。
// Send the selected text to your AI/ML API for TTS
const response = await fetch('https://api.aimlapi.com/tts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${AIML_API_KEY}`, // Replace with your actual API key
  },
  body: JSON.stringify({
    model: '#g1_aura-asteria-en',  // Replace with your specific model if needed
    text: selectedText
  })
});
  • 检索音频:从 IndexedDB 中获取音频 blob 进行播放。
try {

  // ...code

  if (!response.ok) {
    throw new Error('API request failed');
  }

  // ...code

} catch (error) {
  console.error('Error:', error);
  askButton.disabled = false;
  askButton.innerText = 'Read Aloud';
  alert('An error occurred while fetching the audio.');
}
  • 删除音频:播放后从数据库中删除音频 blob 以释放空间。
// Play the audio
audio.play();

清理和用户体验

  • 覆盖删除:如果用户单击其他地方或取消选择文本,则删除覆盖。
// Open IndexedDB
const db = await openDatabase();
const audioId = 'audio_' + Date.now(); // Generate a unique ID for the audio
  • 重新启用按钮:确保处理完成后重新启用“朗读”按钮。
  • 用户反馈:提供视觉提示,例如将按钮文本更改为“正在加载...”,以通知用户处理正在进行中。

完整代码:

// Save audio blob to IndexedDB
await saveAudioToIndexedDB(db, audioId, audioBlob);

实现 IndexedDB 函数

IndexedDB 是一个强大的客户端存储系统,它允许我们存储大量数据,包括文件和 blob。

要实现的功能

您需要创建四个主要函数来与 IndexedDB 交互:

  • openDatabase():打开与数据库的连接并创建对象存储(如果不存在)。
mkdir my-first-chrome-extension
cd my-first-chrome-extension
  • saveAudioToIndexedDB():使用唯一 ID 保存音频 blob。
touch manifest.json
touch scripts.js
touch styles.css
  • getAudioFromIndexedDB():使用其 ID 检索音频 blob。
{
  "manifest_version": 3,
  "name": "Read Aloud",
  "version": "1.0",
  "description": "Read Aloud anything in any tab",
  "host_permissions": [
    "*://*.aimlapi.com/*"
],
  "permissions": [
      "activeTab"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["scripts.js"],
      "css": ["styles.css"]
    }
  ],
  "icons": {
    "16": "icons/icon.png",
    "48": "icons/icon.png",
    "128": "icons/icon.png"
  }
}
  • deleteAudioFromIndexedDB():播放后删除音频 blob。
// Set your AIML_API_KEY key
const AIML_API_KEY = ''; // Replace with your AIML_API_KEY key

// Create the overlay
const overlay = document.createElement('div');
overlay.id = 'read-aloud-overlay';

// Create the "Read Aloud" button
const askButton = document.createElement('button');
askButton.id = 'read-aloud-button';
askButton.innerText = 'Read Aloud';

// Append the button to the overlay
overlay.appendChild(askButton);

// Variables to store selected text and range
let selectedText = '';
let selectedRange = null;

关键概念

  • 事务:与 IndexedDB 的所有交互都发生在事务中。确保指定正确的事务模式(只读或读写)。
  • 对象存储:与 SQL 数据库中的表类似,对象存储保存数据。我们将使用名为“audios”的对象存储。
  • 错误处理:始终处理数据库操作的错误,以防止意外行为。

使用 styles.css 进行样式设置

为了提供无缝的用户体验,您的扩展程序应该有一个干净直观的界面。

设置叠加层和按钮的样式

定义样式:

  • 叠加定位:绝对定位将叠加放置在所选文本附近。
document.addEventListener('mouseup', (event) => {
  console.log('mouseup event: ', event);
  //...code
}
  • 按钮外观:设计“朗读”按钮的样式以匹配叠加层并易于点击。
const selection = window.getSelection();
const text = selection.toString().trim();
if (text !== '') {
  const range = selection.getRangeAt(0);
  const rect = range.getBoundingClientRect();
  • 悬停效果:通过按钮上的悬停效果增强用户交互。
// Set the position of the overlay
overlay.style.top = `${window.scrollY + rect.top - 50}px`; // Adjust as needed
overlay.style.left = `${window.scrollX + rect.left + rect.width / 2 - 70}px`; // Adjust to center the overlay

selectedText = text;
selectedRange = range;
  • 禁用状态:直观地指示按钮何时被禁用。
// Remove existing overlay if any
const existingOverlay = document.getElementById('read-aloud-overlay');
if (existingOverlay) {
  existingOverlay.remove();
}

// Append the overlay to the document body
document.body.appendChild(overlay);
} else {
  // Remove overlay if no text is selected
  const existingOverlay = document.getElementById('read-aloud-overlay');
  if (existingOverlay) {
    existingOverlay.remove();
  }
}

获取并设置您的 API 密钥

要与 AI/ML API 和 Deepgram Aura 模型交互,您需要一个 API 密钥。

获取 API 密钥的步骤

  • 访问 AI/ML API 平台:导航至 aimlapi.com

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

  • 登录:点击“获取 API 密钥”并使用您的 Google 帐户登录。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

  • 访问仪表板:登录后,您将被重定向到仪表板。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

  • 创建 API 密钥:进入“密钥管理”选项卡,然后单击“创建 API 密钥”。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

  • 复制 API 密钥:生成后,复制您的 API 密钥。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

在您的扩展中设置 API 密钥

  • 安全注意事项:如果您打算分发扩展程序,切勿将 API 密钥硬编码到脚本中。考虑使用环境变量或提示用户输入 API 密钥。
mkdir my-first-chrome-extension
cd my-first-chrome-extension

现在输入您的 API 密钥:

touch manifest.json
touch scripts.js
touch styles.css

但它不会立即起作用。在 Chrome 扩展程序中使用 .env 需要其他额外的配置。我们将在接下来的教程中讨论这个问题。

  • 用于测试:在 script.js 中,将 API 密钥分配给处理 API 请求身份验证的变量。
{
  "manifest_version": 3,
  "name": "Read Aloud",
  "version": "1.0",
  "description": "Read Aloud anything in any tab",
  "host_permissions": [
    "*://*.aimlapi.com/*"
],
  "permissions": [
      "activeTab"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["scripts.js"],
      "css": ["styles.css"]
    }
  ],
  "icons": {
    "16": "icons/icon.png",
    "48": "icons/icon.png",
    "128": "icons/icon.png"
  }
}

运行和测试扩展

所有组件就位后,就可以将扩展程序加载到 Chrome 浏览器中并查看其运行情况了。

加载扩展

  • 打开扩展页面:在 Chrome 中,导航至 chrome://extensions/。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

启用开发者模式:切换右上角的“开发者模式”开关。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

  • 加载解压的扩展程序:单击“加载解压的”并选择您的 my-first-chrome-extension 文件夹。 (附:在我的例子中它是 aimlapi-tutorial-one)。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

  • 验证安装:扩展程序现在应该显示在列表中及其名称和图标。

测试功能

  • 导航到网页:打开包含文本内容的网页,例如文章或博客文章。
  • 选择文本:突出显示段落或句子。
  • 与叠加层交互:“正在加载...”叠加层应出现在所选文本上方。启动文本转语音过程时请等待几秒钟。
  • 听:经过短暂的处理时间,您应该听到人工智能语音朗读文本。

故障排除技巧

  • 覆盖不出现:检查在manifest.json中是否正确指定了content_scripts。
  • 无音频播放:验证您的 API 密钥设置正确并且 API 请求是否成功。
  • 控制台错误:使用浏览器的开发者工具检查任何 JavaScript 错误或网络问题。

项目概要

在本教程中,我们:

  • 设置开发环境:为 Chrome 扩展创建必要的项目结构和文件。
  • 配置的manifest.json:定义必要的元数据和权限,了解每个字段的重要性。
  • 开发了scripts.js:概述了处理文本选择、与AI/ML API交互以及管理音频播放的逻辑。
  • 实现了 IndexedDB 集成:学习了如何使用 IndexedDB 在本地存储和检索音频文件。
  • 使用 styles.css 设计扩展:应用 CSS 来增强用户界面并改善用户体验。
  • 获取并设置 API 密钥:从 AI/ML API 平台获取 API 密钥并将其安全地集成到我们的扩展中。
  • 加载并测试扩展程序:在 Chrome 中部署扩展程序并在实时网页上验证其功能。
  • 讨论最佳实践:强调扩展开发中安全性、用户体验和错误处理的重要性。

下一步

有了扎实的基础,你就可以进一步增强你的延伸:

  • 添加自定义选项:允许用户选择不同的声音或语言。
  • 改进错误处理:在 API 不可用时提供用户友好的消息和后备选项。
  • 优化性能:实施缓存策略或优化 API 请求以减少延迟。
  • 发布您的扩展程序:通过在 Chrome 应用商店中发布您的作品来与他人分享。

Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration


结论

恭喜您构建了一个集成了高级 AI 功能的 Chrome 扩展!该项目展示了如何将网络技术与强大的 API 相结合来创建引人入胜且易于访问的用户体验。您现在已经具备了开发和扩展此扩展或创建利用 AI/ML API 的全新扩展的知识。

Github 上提供了完整的实现; https://github.com/TechWithAbee/Building-a-Chrome-Extension-from-Scratch-with-AI-ML-API-Deepgram-Aura-and-IndexDB-Integration


如果您有任何疑问或需要进一步帮助,请随时通过电子邮件联系 abdibrokhim@gmail.com。

以上是使用 AI/ML API、Deepgram Aura 和 IndexedDB 集成从头开始构建 Chrome 扩展的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn