0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Firebase + Perspective API でチャットに不適切発言フィルターを実装する方法

Posted at

はじめに

Firebase Realtime Detabaseを使ったチャット機能に、Googleの Perspective API を使って「不適切発言」をブロックする機能を Firebase Functions + Nuxt 3 で実装した手順をまとめます。

目的

以下のようにユーザーが不適切な発言をしようとしたら送信されないチャットを作成する。
image.png

手順

1.Perspective APIの有効化

1.https://www.perspectiveapi.com/ にアクセス

2.以下のgoogle formを入力しAPIのアクセスをリクエストする

3.Google Cloud Consoleにログインして APIキー発行&Perspective Comment Analyzer APIの有効化

2.Firebase Functionsの実装

この関数では、ユーザーのテキストを Perspective API に送り、有害度スコア(TOXICITY)を取得します。

  • もしスコアが 0.7 以上であれば「不適切」と判断してブロック
import { onCall } from "firebase-functions/v2/https";
import { HttpsError } from "firebase-functions/v2/https";

export const checkChatModeration = onCall({ region: "us-central1" }, async (request) => {
  const text: string = request.data?.text;
  const API_KEY = process.env.PERSPECTIVE_API_KEY;

  if (!API_KEY) {
    throw new HttpsError("failed-precondition", "APIキー未設定");
  }

  if (!text || typeof text !== "string") {
    throw new HttpsError("invalid-argument", "テキストが不正");
  }

  const url = `https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key=${API_KEY}`;

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        comment: { text },
        languages: ["ja"],// 日本語として評価
        requestedAttributes: { TOXICITY: {} },// 有害性スコアのみ取得
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`APIエラー: ${errorText}`);
    }

    const data = await response.json();
    const score = data.attributeScores.TOXICITY.summaryScore.value;
  // スコアが0.7以上なら不適切と判断してブロック
    if (score >= 0.7) {
      return { ok: false, message: "❗️ 不適切な発言が検出されました。", score };
    }
// 問題なければOKレスポンス
    return { ok: true, message: "OKな内容です。", score };
  } catch (err: any) {
    console.error("Perspective API エラー:", err.message);
    throw new HttpsError("internal", "モデレーションエラー");
  }
});

3. クライアント(Nuxt)から checkChatModeration を呼び出す

import { getFunctions, httpsCallable } from "firebase/functions";

// Firebase Functions のインスタンスを取得
const functions = getFunctions(firebaseApp);

// Callable Function を呼び出す
const checkModeration = httpsCallable(functions, "checkChatModeration");

// テキストを渡してチェック
const result = await checkModeration({ text: userInput });
if (!result.data.ok) {
  alert(result.data.message);
  return;
}

まとめ

  • Perspective API を使い、不適切発言判定がをすることができる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?