メインコンテンツへスキップ
見出し画像

🧠 歌詞を「感情」で読み解く!AIでフレーズ単位の感情分析を自動化してみた【Colab + DeBERTa】

    🎯 このツールでできること


    • 歌詞を4行ずつのフレーズ単位で区切って、感情をAIで自動判定

    • 感情の種類(8分類)+ 強度(Strong / Medium / Weak)も出力

    • 楽曲全体の感情傾向をスコア化し、上位2感情・4感情に絞ったデータも自動生成


    🔗 使用するJSONファイルは「Whisperコード」から出力可能!

    本ツールで使用する入力ファイル(JSON形式)は、
    別記事で紹介しているWhisper音声認識+歌詞整形ツールを使えば自動生成できます。

    [
      { "start": 12.3, "end": 14.5, "text": "風が吹いた日" },
      { "start": 15.0, "end": 17.2, "text": "心が少し揺れた" }
    ]

    このように、`start`, `end`, `text` の3要素を含む形式であれば、そのまま使えます。

    🔗 Whisper×歌詞整形ツール紹介記事
    以下の記事で紹介しているコードで対応するJsonファイルを生成できます。


    🧠 分析される8つの感情カテゴリ

    • Joy(喜び)

    • Sadness(悲しみ)

    • Anger(怒り)

    • Fear(恐れ)

    • Surprise(驚き)

    • Disgust(嫌悪)

    • Trust(信頼)

    • Anticipation(期待)

    これらがすべて、各フレーズごとに英語+強度ラベル付きで出力されます。


    📊 出力されるファイル一覧

    | ファイル名                                                | 内容                                             |
    |----------------------------------------------|-------------------------------------|
    | `phrase_emotion_analysis_complete.json` | フル感情データ付きの全行出力 |
    | `phrase_emotion_analysis_top2.json`   | 上位2感情に絞ったデータ          |
    | `phrase_emotion_analysis_top4.json`        | 上位4感情に絞ったデータ           |
    | `phrase_emotion_analysis_summary.json` | 総合スコア・感情統計まとめ     |


    💾 実行はColabでOK!コピペするだけ

    以下のコードをGoogle Colabに貼り付けて実行すれば、
    アップロードしたJSON歌詞ファイルに対して、感情分析が行われます。


    🧠 そのまま使えるColabコード

    # ===============================
    # パッケージインストール(初回のみ)
    # ===============================
    !pip install deberta-emotion-predictor transformers torch
    
    import json
    from collections import defaultdict
    from google.colab import files
    from deberta_emotion_predictor import DeBERTaEmotionPredictor
    import time
    
    print("=== フレーズ単位感情分析システム ===")
    
    # Step 1: ファイルアップロード
    uploaded = files.upload()
    input_filename = list(uploaded.keys())[0]
    
    with open(input_filename, 'r', encoding='utf-8') as f:
        lyrics_data = json.load(f)
    
    # Step 2: フレーズ単位でのまとめ処理
    def group_lyrics_by_phrase(lyrics_data, lines_per_phrase=4):
        grouped_data = []
        temp_texts = []
        temp_entries = []
    
        for entry in lyrics_data:
            if 'text' in entry and entry['text'].strip():
                temp_texts.append(entry['text'].strip())
                temp_entries.append(entry)
    
                if len(temp_texts) >= lines_per_phrase:
                    grouped_data.append({
                        'phrase_text': " ".join(temp_texts),
                        'start_time': temp_entries[0]['start'],
                        'end_time': temp_entries[-1]['end'],
                        'individual_lines': temp_entries.copy()
                    })
                    temp_texts, temp_entries = [], []
    
        if temp_texts:
            grouped_data.append({
                'phrase_text': " ".join(temp_texts),
                'start_time': temp_entries[0]['start'],
                'end_time': temp_entries[-1]['end'],
                'individual_lines': temp_entries.copy()
            })
    
        return grouped_data
    
    phrase_data = group_lyrics_by_phrase(lyrics_data, lines_per_phrase=4)
    print(f"フレーズ数: {len(phrase_data)}")
    
    # Step 3: 感情予測器と分類関数
    predictor = DeBERTaEmotionPredictor()
    
    def intensity_classification(score):
        if score >= 0.75: return "Strong"
        elif score >= 0.5: return "Medium"
        else: return "Weak"
    
    intensity_map = {'Weak': 1, 'Medium': 2, 'Strong': 3}
    
    # Step 4: 感情分析実行
    start_time = time.time()
    
    for i, phrase_entry in enumerate(phrase_data):
        print(f"分析中... ({i+1}/{len(phrase_data)}) - {phrase_entry['phrase_text'][:30]}...")
        emotion_scores = predictor.predict_emotions(phrase_entry['phrase_text'])
    
        for line_entry in phrase_entry['individual_lines']:
            line_entry['emotions'] = {}
            for eng_label, score in emotion_scores.items():
                try:
                    score_val = float(score)
                    intensity = intensity_classification(score_val)
                    if 'predicted_label' in eng_label or 'positive_probability' in eng_label:
                        line_entry['emotions'][eng_label] = intensity
                    else:
                        line_entry['emotions'][f'{eng_label}_predicted_label'] = intensity
                        line_entry['emotions'][f'{eng_label}_positive_probability'] = intensity
                except (TypeError, ValueError):
                    continue
    
    end_time = time.time()
    
    # Step 5: 統計処理
    base_emotions = ['Joy', 'Sadness', 'Anger', 'Fear', 'Surprise', 'Disgust', 'Trust', 'Anticipation']
    consolidated_scores = defaultdict(int)
    
    for entry in lyrics_data:
        if 'emotions' in entry:
            for emotion in base_emotions:
                predicted = f'{emotion}_predicted_label'
                prob = f'{emotion}_positive_probability'
                consolidated_scores[emotion] += max(
                    intensity_map.get(entry['emotions'].get(predicted, 'Weak'), 0),
                    intensity_map.get(entry['emotions'].get(prob, 'Weak'), 0)
                )
    
    sorted_emotions = sorted(consolidated_scores.items(), key=lambda x: x[1], reverse=True)
    emotion_map = {
        "Joy": "喜び", "Trust": "信頼", "Fear": "恐れ", "Surprise": "驚き",
        "Sadness": "悲しみ", "Disgust": "嫌悪", "Anger": "怒り", "Anticipation": "期待"
    }
    
    # Step 6a: 上位2感情抽出
    top_2_emotions = sorted_emotions[:2]
    top_4_emotions = sorted_emotions[:4]
    
    def filter_emotions(data, selected_emotions):
        result = []
        for entry in data:
            filtered = {'start': entry['start'], 'end': entry['end'], 'text': entry['text']}
            if 'emotions' in entry:
                emo = {}
                for emotion, _ in selected_emotions:
                    p = f'{emotion}_predicted_label'
                    pr = f'{emotion}_positive_probability'
                    val1 = entry['emotions'].get(p, 'Weak')
                    val2 = entry['emotions'].get(pr, 'Weak')
                    emo[emotion] = val1 if intensity_map[val1] >= intensity_map[val2] else val2
                if emo:
                    filtered['emotions'] = emo
            result.append(filtered)
        return result
    
    filtered_lyrics_top2 = filter_emotions(lyrics_data, top_2_emotions)
    filtered_lyrics_top4 = filter_emotions(lyrics_data, top_4_emotions)
    
    # Step 7: 出力とダウンロード
    with open('phrase_emotion_analysis_complete.json', 'w', encoding='utf-8') as f:
        json.dump(lyrics_data, f, ensure_ascii=False, indent=2)
    with open('phrase_emotion_analysis_top2.json', 'w', encoding='utf-8') as f:
        json.dump(filtered_lyrics_top2, f, ensure_ascii=False, indent=2)
    with open('phrase_emotion_analysis_top4.json', 'w', encoding='utf-8') as f:
        json.dump(filtered_lyrics_top4, f, ensure_ascii=False, indent=2)
    
    summary = {
        "processing_method": "フレーズ単位感情分析",
        "intensity_label_format": "Strong / Medium / Weak",
        "total_phrases": len(phrase_data),
        "processing_time_seconds": round(end_time - start_time, 2),
        "total_lyrics_lines": len([e for e in lyrics_data if e.get('text', '').strip()]),
        "emotion_statistics": dict(consolidated_scores),
        "sorted_emotion_ranking": [
            {
                "rank": i,
                "emotion": emotion,
                "japanese": emotion_map.get(emotion, emotion),
                "score": score
            } for i, (emotion, score) in enumerate(sorted_emotions, 1)
        ],
        "top_2_emotions": {
            "primary": {
                "emotion": top_2_emotions[0][0],
                "japanese": emotion_map.get(top_2_emotions[0][0], top_2_emotions[0][0]),
                "score": top_2_emotions[0][1]
            },
            "secondary": {
                "emotion": top_2_emotions[1][0],
                "japanese": emotion_map.get(top_2_emotions[1][0], top_2_emotions[1][0]),
                "score": top_2_emotions[1][1]
            }
        }
    }
    with open('phrase_emotion_analysis_summary.json', 'w', encoding='utf-8') as f:
        json.dump(summary, f, ensure_ascii=False, indent=2)
    
    files.download('phrase_emotion_analysis_complete.json')
    files.download('phrase_emotion_analysis_top2.json')
    files.download('phrase_emotion_analysis_top4.json')
    files.download('phrase_emotion_analysis_summary.json')
    
    print("\n✅ 感情分析 完了(Strong / Medium / Weak)")

    ✨ 次にやってみたら面白いかなと思っていること

    • After Effectsで感情に応じた演出を割り当てる(例:Joy → 明るい背景、Anger → グリッチ)

    • 上位2感情をもとにMV全体の構成を組み立てる

    • 複数曲を感情ベースで分類・比較する


    📍 MV Makerシリーズ公式サイト
    📍 Whisperベースの字幕作成&連携記事はこちら


     
     
    理学療法士×プログラマー。AIで作曲・MV・歌詞字幕づくりを自動化し、その過程を数字つきで記録しています。新しいAIツールに振り回されないコツは、原理原則をつかむこと。はじめての方は↓ https://note.com/soundinspire/n/n147fe55750b1

    あなたへのおすすめ