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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import requests
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
class TextAnalyzer:
|
| 6 |
+
"""
|
| 7 |
+
テキストのハラスメント検出と会話評価を行うクラス。
|
| 8 |
+
"""
|
| 9 |
+
def __init__(self, file_path, keywords):
|
| 10 |
+
"""
|
| 11 |
+
TextAnalyzer クラスのコンストラクタ。
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
file_path (str): 分析するテキストファイルのパス。
|
| 15 |
+
keywords (list): ハラスメント検出に使用するキーワードのリスト。
|
| 16 |
+
"""
|
| 17 |
+
self.file_path = file_path
|
| 18 |
+
self.keywords = keywords
|
| 19 |
+
self.text_content = None # テキストファイルの内容を格納
|
| 20 |
+
self.harassment_detected = False # ハラスメントが検出されたかどうか
|
| 21 |
+
self.harassment_keywords = [] # 検出されたハラスメントキーワードのリスト
|
| 22 |
+
self.deepseek_analysis = {} # DeepSeek API による分析結果を格納する辞書
|
| 23 |
+
self.api_key = None # DeepSeek API キー
|
| 24 |
+
|
| 25 |
+
def load_text(self):
|
| 26 |
+
"""
|
| 27 |
+
テキストファイルを読み込み、その内容を self.text_content に格納する。
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
bool: ファイルの読み込みに成功した場合は True、失敗した場合は False。
|
| 31 |
+
"""
|
| 32 |
+
try:
|
| 33 |
+
with open(self.file_path, 'r', encoding='utf-8') as file:
|
| 34 |
+
self.text_content = file.read()
|
| 35 |
+
return True
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"ファイル読み込みエラー: {e}")
|
| 38 |
+
return False
|
| 39 |
+
|
| 40 |
+
def detect_harassment(self):
|
| 41 |
+
"""
|
| 42 |
+
テキスト内容からハラスメントを検出する。
|
| 43 |
+
|
| 44 |
+
Returns:
|
| 45 |
+
bool: ハラスメントが検出された場合は True、それ以外は False。
|
| 46 |
+
"""
|
| 47 |
+
if not self.text_content:
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
self.harassment_keywords = []
|
| 51 |
+
for keyword in self.keywords:
|
| 52 |
+
if keyword in self.text_content:
|
| 53 |
+
self.harassment_detected = True
|
| 54 |
+
self.harassment_keywords.append(keyword)
|
| 55 |
+
|
| 56 |
+
return self.harassment_detected
|
| 57 |
+
|
| 58 |
+
def analyze_with_deepseek(self, api_key=None, api_url="https://api.deepseek.com/v1/chat/completions"):
|
| 59 |
+
"""
|
| 60 |
+
DeepSeek API を使用して会話を分析する。会話レベルやハラスメントの詳細な検出を行う。
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
api_key (str, optional): DeepSeek API キー。指定されない場合は環境変数から取得。
|
| 64 |
+
api_url (str, optional): DeepSeek API の URL。デフォルトは標準のチャット補完エンドポイント。
|
| 65 |
+
|
| 66 |
+
Returns:
|
| 67 |
+
bool: 分析に成功した場合は True、失敗した場合は False。
|
| 68 |
+
"""
|
| 69 |
+
if not self.text_content:
|
| 70 |
+
return False
|
| 71 |
+
|
| 72 |
+
# 提供された API キーを使用するか、環境変数から取得する
|
| 73 |
+
if api_key:
|
| 74 |
+
self.api_key = api_key
|
| 75 |
+
else:
|
| 76 |
+
self.api_key = os.environ.get("DEEPSEEK_API_KEY")
|
| 77 |
+
if not self.api_key:
|
| 78 |
+
print("DeepSeek API キーが提供されておらず、環境変数にも見つかりませんでした。")
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
headers = {
|
| 82 |
+
"Content-Type": "application/json",
|
| 83 |
+
"Authorization": f"Bearer {self.api_key}"
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
prompt = f"""
|
| 87 |
+
以下の会話を分析し、結果を JSON 形式で返してください。1 から 10 のスケールで評価し、10 が最高です。
|
| 88 |
+
厳密に評価してください。ハラスメントが存在する場合は、その種類を具体的に記述してください。
|
| 89 |
+
評価基準:
|
| 90 |
+
1. conversationLevel: 会話のレベル (初心者、中級者、上級者)。
|
| 91 |
+
2. harassmentPresent: 会話にハラスメント表現が含まれているかどうか (true/false)。
|
| 92 |
+
3. harassmentType: ハラスメントが存在する場合、その種類を具体的に記述。
|
| 93 |
+
4. topicAppropriateness: 会話のトピックが適切かどうか。
|
| 94 |
+
5. improvementSuggestions: 会話を改善するための具体的な提案。
|
| 95 |
+
6. repetition: 同じことがどの程度繰り返されているか。(1-10)
|
| 96 |
+
7. pleasantConversation: 会話がどの程度心地よいか。(1-10)
|
| 97 |
+
8. blameOrHarassment: 会話がどの程度相手を責めたり、ハラスメントをしているか。(1-10)
|
| 98 |
+
|
| 99 |
+
会話内容:
|
| 100 |
+
{self.text_content}
|
| 101 |
+
|
| 102 |
+
JSON 形式のみを返してください。
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
data = {
|
| 106 |
+
"model": "deepseek-chat",
|
| 107 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 108 |
+
"response_format": {"type": "json_object"}
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
response = requests.post(api_url, headers=headers, json=data)
|
| 113 |
+
response.raise_for_status()
|
| 114 |
+
|
| 115 |
+
result = response.json()
|
| 116 |
+
deepseek_response = json.loads(result["choices"][0]["message"]["content"])
|
| 117 |
+
|
| 118 |
+
# 指定されたキーを使用して、インスタンス変数に値を割り当てる
|
| 119 |
+
self.deepseek_analysis = {
|
| 120 |
+
"conversationLevel": deepseek_response.get("conversationLevel"),
|
| 121 |
+
"harassmentPresent": deepseek_response.get("harassmentPresent"),
|
| 122 |
+
"harassmentType": deepseek_response.get("harassmentType"),
|
| 123 |
+
"topicAppropriateness": deepseek_response.get("topicAppropriateness"),
|
| 124 |
+
"improvementSuggestions": deepseek_response.get("improvementSuggestions"),
|
| 125 |
+
"repetition": deepseek_response.get("repetition"),
|
| 126 |
+
"pleasantConversation": deepseek_response.get("pleasantConversation"),
|
| 127 |
+
"blameOrHarassment": deepseek_response.get("blameOrHarassment"),
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
return True
|
| 131 |
+
except requests.exceptions.RequestException as e:
|
| 132 |
+
print(f"DeepSeek API リクエストエラー: {e}")
|
| 133 |
+
return False
|
| 134 |
+
except json.JSONDecodeError as e:
|
| 135 |
+
print(f"DeepSeek API レスポンスの JSON デコードエラー: {e}")
|
| 136 |
+
print(f"レスポンス内容: {response.text}")
|
| 137 |
+
return False
|
| 138 |
+
except KeyError as e:
|
| 139 |
+
print(f"DeepSeek API レスポンスのキーエラー: {e}")
|
| 140 |
+
print(f"レスポンス内容: {response.text}")
|
| 141 |
+
return False
|
| 142 |
+
except Exception as e:
|
| 143 |
+
print(f"DeepSeek API エラー: {e}")
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
def get_analysis_results(self):
|
| 147 |
+
"""
|
| 148 |
+
分析結果を返す。
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
dict: 分析結果を含む辞書。
|
| 152 |
+
"""
|
| 153 |
+
results = {
|
| 154 |
+
"text_content": self.text_content,
|
| 155 |
+
"basic_harassment_detection": {
|
| 156 |
+
"detected": self.harassment_detected,
|
| 157 |
+
"matching_keywords": self.harassment_keywords
|
| 158 |
+
},
|
| 159 |
+
"deepseek_analysis": self.deepseek_analysis
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
return results
|
| 163 |
+
|
| 164 |
+
def analyze(self, api_key=None):
|
| 165 |
+
"""
|
| 166 |
+
すべての分析を実行し、結果を返す。
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
api_key (str, optional): DeepSeek API キー。
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
dict: 分析結果またはエラーメッセージを含む辞書。
|
| 173 |
+
"""
|
| 174 |
+
if not self.load_text():
|
| 175 |
+
return {"error": "テキストファイルの読み込みに失敗しました。"}
|
| 176 |
+
|
| 177 |
+
self.detect_harassment()
|
| 178 |
+
|
| 179 |
+
if not self.analyze_with_deepseek(api_key):
|
| 180 |
+
return {"error": "DeepSeek API 分析に失敗しました。"}
|
| 181 |
+
|
| 182 |
+
return self.get_analysis_results()
|
| 183 |
+
|
| 184 |
+
'''
|
| 185 |
+
# 使用例
|
| 186 |
+
if __name__ == "__main__":
|
| 187 |
+
# ハラスメント検出用のキーワード例
|
| 188 |
+
harassment_keywords = [
|
| 189 |
+
"バカ", "馬鹿", "アホ", "死ね", "クソ", "うざい",
|
| 190 |
+
"きもい", "キモい", "ブス", "デブ", "ハゲ",
|
| 191 |
+
"セクハラ", "パワハラ", "モラハラ"
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
# 分析インスタンスの作成
|
| 195 |
+
analyzer = TextAnalyzer("./2.txt", harassment_keywords)
|
| 196 |
+
|
| 197 |
+
# DeepSeek API キー (環境変数から取得するか、直接渡す)
|
| 198 |
+
# api_key = os.environ.get("DEEPSEEK_API_KEY")
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# 分析の実行
|
| 202 |
+
results = analyzer.analyze(api_key=api_key)
|
| 203 |
+
|
| 204 |
+
# 結果の出力
|
| 205 |
+
print(json.dumps(results, ensure_ascii=False, indent=2))
|
| 206 |
+
|
| 207 |
+
# 特定の値へのアクセス例
|
| 208 |
+
if "deepseek_analysis" in results and results["deepseek_analysis"]:
|
| 209 |
+
deepseek_data = results["deepseek_analysis"]
|
| 210 |
+
conversation_level = deepseek_data.get("conversationLevel")
|
| 211 |
+
harassment_present = deepseek_data.get("harassmentPresent")
|
| 212 |
+
harassment_type = deepseek_data.get("harassmentType")
|
| 213 |
+
repetition = deepseek_data.get("repetition")
|
| 214 |
+
pleasantConversation = deepseek_data.get("pleasantConversation")
|
| 215 |
+
blameOrHarassment = deepseek_data.get("blameOrHarassment")
|
| 216 |
+
|
| 217 |
+
print("\n--- DeepSeek 分析結果 ---")
|
| 218 |
+
print(f"会話レベル: {conversation_level}")
|
| 219 |
+
print(f"ハラスメントの有無: {harassment_present}")
|
| 220 |
+
print(f"ハラスメントの種類: {harassment_type}")
|
| 221 |
+
print(f"繰り返しの程度: {repetition}")
|
| 222 |
+
print(f"会話の心地よさ: {pleasantConversation}")
|
| 223 |
+
print(f"非難またはハラスメントの程度: {blameOrHarassment}")
|
| 224 |
+
'''
|