☠️

Perspective APIで文章の有害度判定を

2025/02/06に公開

tl:dr

Google Cloudのperspective apiを使って文章の危険度判定をやってみた.

背景

AIが生成した文章の危険度判定をやりたい!
Llama Guardは日本語にしか対応してないし,多言語対応してるperspective apiを使ってみよう

方法

  1. Perspective APIのスタートガイドに則って,GCPプロジェクトの作成をした後,apiのリクエストをgoogle formで送信.
  2. メールに記載されている Go Enable API のボタンをクリックしてapiを有効化
  3. pythonでライブラリのインストール
    pip install requests python-dotenv
    
  4. APIキーを.envに保存
    PERSPECTIVE_API_KEY="your_api_key"
    
  5. pythonのコードを作成
    import os
    import requests
    import json
    from dotenv import load_dotenv
    
    # .env ファイルを読み込む
    load_dotenv()
    
    # APIキーの取得
    API_KEY = os.getenv("PERSPECTIVE_API_KEY")
    if not API_KEY:
        raise ValueError("PERSPECTIVE_API_KEY が .env に設定されていません。")
    
    # Perspective APIのエンドポイント
    PERSPECTIVE_API_URL = "https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze"
    
    def analyze_text(text):
        """Perspective APIを使ってテキストのトキシシティ(毒性)を分析する"""
        headers = {"Content-Type": "application/json"}
        data = {
            "comment": {"text": text},
            "languages": ["en"],  # 日本語にするなら["ja"]
            "requestedAttributes": {"TOXICITY": {}},
        }
        
        response = requests.post(
            f"{PERSPECTIVE_API_URL}?key={API_KEY}",
          headers=headers,
            json=data
        )
    
        if response.status_code == 200:
            result = response.json()
            toxicity_score = result["attributeScores"]["TOXICITY"]["summaryScore"]["value"]
            return toxicity_score
        else:
            print("Error:", response.status_code, response.text)
            return None
    
    # 例: テキストを分析
    text = "You are so stupid!"
    toxicity = analyze_text(text)
    
    if toxicity is not None:
        print(f"Toxicity Score: {toxicity:.2f}")
    else:
        print("エラーが発生しました")
    
    実行結果の例
    Toxicity Score: 0.87 (数値が1に近いほど危険な文章であることを示す)
    

以上!

Discussion