ClaudeでAIを利用したメンタルサポートをするためのPythonコードを出力してみた
ClaudeでAIを利用したメンタルサポートをするためのPythonコードを出力してみた
import re
import random
import datetime
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import json
@dataclass
class MoodEntry:
"""気分の記録用データクラス"""
timestamp: datetime.datetime
mood_score: int # 1-10のスケール
emotions: List[str]
notes: str
class EmotionAnalyzer:
"""感情分析クラス"""
def __init__(self):
# 感情キーワード辞書
self.emotion_keywords = {
'happy': ['嬉しい', '楽しい', '幸せ', '喜び', '良い', 'いい', '最高', 'ハッピー'],
'sad': ['悲しい', 'つらい', '辛い', '寂しい', '落ち込む', '憂鬱', '泣きたい'],
'anxious': ['不安', '心配', '怖い', '恐れ', 'ドキドキ', '緊張', '焦る'],
'angry': ['怒り', '腹立つ', 'イライラ', 'ムカつく', '頭にくる', '憤り'],
'stressed': ['ストレス', '疲れ', '疲労', 'しんどい', 'きつい', '大変', 'プレッシャー'],
'lonely': ['孤独', 'ひとり', '一人', '孤立', '寂しい', '孤独感'],
'confused': ['混乱', 'わからない', '困った', '迷う', '悩む', 'どうしよう']
}
def analyze_emotion(self, text: str) -> Dict[str, float]:
"""テキストから感情を分析"""
text = text.lower()
emotion_scores = {}
for emotion, keywords in self.emotion_keywords.items():
score = 0
for keyword in keywords:
if keyword in text:
score += 1
emotion_scores[emotion] = score / len(keywords) if keywords else 0
return emotion_scores
def get_dominant_emotion(self, text: str) -> str:
"""最も強い感情を取得"""
scores = self.analyze_emotion(text)
if not any(scores.values()):
return 'neutral'
return max(scores, key=scores.get)
class ResponseGenerator:
"""応答生成クラス"""
def __init__(self):
self.responses = {
'happy': [
"それは素晴らしいですね!その気持ちを大切にしてください。",
"嬉しい気持ちが伝わってきます。今の幸せな瞬間を味わってくださいね。",
"ポジティブな気持ちですね!その調子で過ごしていきましょう。"
],
'sad': [
"辛い気持ち、よくわかります。一人じゃありませんよ。",
"悲しい時は無理に元気になろうとしなくて大丈夫です。今の気持ちを受け入れましょう。",
"今は苦しい時期かもしれませんが、必ず乗り越えられる日が来ます。"
],
'anxious': [
"不安な気持ち、理解できます。深呼吸をしてみませんか?",
"心配事があるときは、まず今この瞬間に集中してみましょう。",
"不安は自然な感情です。一つずつ整理していけば大丈夫ですよ。"
],
'angry': [
"怒りの感情も大切な信号です。何が原因か一緒に考えてみましょう。",
"イライラする気持ち、よくわかります。少し落ち着く時間を取ってみませんか?",
"怒りは正当な感情です。ただ、それをどう表現するかが大切ですね。"
],
'stressed': [
"ストレスが溜まっているようですね。少し休憩は取れていますか?",
"疲れた時は、自分をいたわることも必要です。無理をしないでくださいね。",
"ストレスは体と心のサインです。リラックスできる時間を作ってみましょう。"
],
'lonely': [
"孤独感を感じているのですね。あなたの気持ちに寄り添いたいです。",
"一人だと感じる時もありますが、あなたを大切に思っている人がいます。",
"孤独な気持ち、辛いですね。でも今こうしてお話しできて嬉しいです。"
],
'confused': [
"混乱している状況、整理するお手伝いをしますよ。",
"わからないことがあるのは当然です。一緒に考えていきましょう。",
"迷いがあるときは、焦らずにゆっくり考えてみませんか?"
],
'neutral': [
"お話を聞かせてください。どんなことでも大丈夫ですよ。",
"今日はいかがお過ごしでしたか?",
"何かお手伝いできることがあれば、遠慮なく言ってくださいね。"
]
}
self.coping_strategies = {
'anxious': [
"4-7-8呼吸法: 4秒で息を吸い、7秒止め、8秒で吐く",
"今この瞬間に集中するマインドフルネス",
"心配事を紙に書き出してみる"
],
'stressed': [
"短時間の散歩や軽い運動",
"好きな音楽を聞く",
"温かいお茶を飲んでリラックス"
],
'sad': [
"感情を日記に書き出す",
"信頼できる人と話をする",
"自分に優しい言葉をかける"
],
'angry': [
"10まで数を数える",
"その場を離れて冷静になる時間を作る",
"運動で発散する"
]
}
def generate_response(self, emotion: str, user_input: str) -> str:
"""感情に基づいて応答を生成"""
base_response = random.choice(self.responses.get(emotion, self.responses['neutral']))
# コーピングストラテジーを提案
if emotion in self.coping_strategies:
strategy = random.choice(self.coping_strategies[emotion])
base_response += f"\n\n💡 試してみてください: {strategy}"
return base_response
class MentalHealthSupport:
"""メンタルヘルスサポートメインクラス"""
def __init__(self):
self.emotion_analyzer = EmotionAnalyzer()
self.response_generator = ResponseGenerator()
self.mood_history: List[MoodEntry] = []
self.session_count = 0
# 緊急時のキーワード
self.crisis_keywords = ['死にたい', '消えたい', '終わりにしたい', '自殺', '自害']
def detect_crisis(self, text: str) -> bool:
"""緊急事態を検出"""
text_lower = text.lower()
return any(keyword in text_lower for keyword in self.crisis_keywords)
def handle_crisis(self) -> str:
"""緊急事態への対応"""
return """
🚨 重要なお知らせ 🚨
あなたの命は大切です。今とても辛い状況にいらっしゃるようですが、一人で抱え込まないでください。
すぐにご利用いただける相談窓口:
📞 いのちの電話: 0570-783-556 (24時間)
📞 よりそいホットライン: 0120-279-338 (24時間)
📞 こころの健康相談統一ダイヤル: 0570-064-556
専門のカウンセラーや医療機関に相談することをお勧めします。
あなたは一人ではありません。必ず助けがあります。
"""
def log_mood(self, mood_score: int, emotions: List[str], notes: str = ""):
"""気分を記録"""
entry = MoodEntry(
timestamp=datetime.datetime.now(),
mood_score=mood_score,
emotions=emotions,
notes=notes
)
self.mood_history.append(entry)
def get_mood_trend(self) -> str:
"""気分の傾向を分析"""
if len(self.mood_history) < 2:
return "まだデータが少ないため、傾向は分析できません。"
recent_scores = [entry.mood_score for entry in self.mood_history[-7:]] # 直近7件
avg_score = sum(recent_scores) / len(recent_scores)
if avg_score >= 7:
return "最近の気分は良好な傾向にあります!"
elif avg_score >= 5:
return "気分は安定している傾向です。"
else:
return "少し気分が落ち込み気味のようです。セルフケアを心がけてみてください。"
def provide_resources(self, emotion: str) -> str:
"""リソースを提供"""
resources = {
'general': [
"📚 メンタルヘルス・ファーストエイド",
"🧘 マインドフルネス瞑想アプリ",
"📝 感情日記をつける習慣"
],
'anxious': [
"😮💨 呼吸法の練習",
"🎵 リラックス音楽",
"🌿 アロマテラピー"
],
'stressed': [
"🏃♀️ 軽い運動・ストレッチ",
"🛁 温かいお風呂",
"📖 好きな本を読む"
]
}
resource_list = resources.get(emotion, resources['general'])
return "🌟 おすすめのセルフケア:\n" + "\n".join(f"• {resource}" for resource in resource_list)
def chat(self, user_input: str) -> str:
"""メインのチャット機能"""
self.session_count += 1
# 緊急事態の検出
if self.detect_crisis(user_input):
return self.handle_crisis()
# 感情分析
dominant_emotion = self.emotion_analyzer.get_dominant_emotion(user_input)
emotion_scores = self.emotion_analyzer.analyze_emotion(user_input)
# 応答生成
response = self.response_generator.generate_response(dominant_emotion, user_input)
# セッション数に応じて追加情報を提供
if self.session_count % 3 == 0:
response += f"\n\n{self.provide_resources(dominant_emotion)}"
if self.session_count % 5 == 0:
response += f"\n\n📊 {self.get_mood_trend()}"
# 気分を記録(簡易版)
mood_score = max(1, min(10, 6 + int(emotion_scores.get('happy', 0) * 3) - int(emotion_scores.get('sad', 0) * 3)))
detected_emotions = [emotion for emotion, score in emotion_scores.items() if score > 0]
self.log_mood(mood_score, detected_emotions, user_input[:100])
return response
def main():
"""メイン実行関数"""
print("🤖 AIメンタルサポート システム")
print("=" * 40)
print("こんにちは!私はあなたのメンタルヘルスをサポートするAIです。")
print("お気持ちや今日の出来事など、何でもお話しください。")
print("終了する場合は 'quit' と入力してください。\n")
support_ai = MentalHealthSupport()
while True:
try:
user_input = input("あなた: ").strip()
if user_input.lower() in ['quit', 'exit', '終了', 'さようなら']:
print("\nAI: お疲れ様でした。またいつでもお話しましょう。")
print("あなたの心の健康を応援しています!🌟")
break
if not user_input:
print("AI: 何かお話ししたいことはありますか?")
continue
# AIの応答を生成
ai_response = support_ai.chat(user_input)
print(f"\nAI: {ai_response}\n")
except KeyboardInterrupt:
print("\n\nAI: またお話しできる日を楽しみにしています。🌸")
break
except Exception as e:
print(f"エラーが発生しました: {e}")
print("もう一度お試しください。")
# 使用例とテスト関数
def test_system():
"""システムのテスト"""
support_ai = MentalHealthSupport()
test_inputs = [
"今日はとても嬉しいことがありました!",
"なんだか不安で心配になってしまいます",
"最近とても疲れていて、ストレスが溜まっています",
"悲しくて涙が止まりません"
]
print("🧪 システムテスト")
print("=" * 30)
for i, test_input in enumerate(test_inputs, 1):
print(f"\nテスト {i}: {test_input}")
response = support_ai.chat(test_input)
print(f"応答: {response}")
print("-" * 30)
if __name__ == "__main__":
# テストを実行する場合は下記のコメントアウトを外してください
# test_system()
# メインプログラムを実行
main()
コメント
コメントを投稿