Spaces:
Runtime error
Runtime error
| import json | |
| import requests | |
| import os | |
| class TextAnalyzer: | |
| """ | |
| テキストのハラスメント検出と会話評価を行うクラス。 | |
| """ | |
| def __init__(self, file_path, keywords): | |
| """ | |
| TextAnalyzer クラスのコンストラクタ。 | |
| Args: | |
| file_path (str): 分析するテキストファイルのパス。 | |
| keywords (list): ハラスメント検出に使用するキーワードのリスト。 | |
| """ | |
| self.file_path = file_path | |
| self.keywords = keywords | |
| self.text_content = None # テキストファイルの内容を格納 | |
| self.harassment_detected = False # ハラスメントが検出されたかどうか | |
| self.harassment_keywords = [] # 検出されたハラスメントキーワードのリスト | |
| self.deepseek_analysis = {} # DeepSeek API による分析結果を格納する辞書 | |
| self.api_key = None | |
| def load_text(self): | |
| """ | |
| テキストファイルを読み込み、その内容を self.text_content に格納する。 | |
| Returns: | |
| bool: ファイルの読み込みに成功した場合は True、失敗した場合は False。 | |
| """ | |
| try: | |
| with open(self.file_path, 'r', encoding='utf-8') as file: | |
| self.text_content = file.read() | |
| return True | |
| except Exception as e: | |
| print(f"ファイル読み込みエラー: {e}") | |
| return False | |
| def detect_harassment(self): | |
| """ | |
| テキスト内容からハラスメントを検出する。 | |
| Returns: | |
| bool: ハラスメントが検出された場合は True、それ以外は False。 | |
| """ | |
| if not self.text_content: | |
| return False | |
| self.harassment_keywords = [] | |
| for keyword in self.keywords: | |
| if keyword in self.text_content: | |
| self.harassment_detected = True | |
| self.harassment_keywords.append(keyword) | |
| return self.harassment_detected | |
| def analyze_with_deepseek(self, api_key=None, api_url="https://api.deepseek.com/v1/chat/completions"): | |
| """ | |
| DeepSeek API を使用して会話を分析する。会話レベルやハラスメントの詳細な検出を行う。 | |
| Args: | |
| api_key (str, optional): DeepSeek API キー。指定されない場合は環境変数から取得。 | |
| api_url (str, optional): DeepSeek API の URL。デフォルトは標準のチャット補完エンドポイント。 | |
| Returns: | |
| bool: 分析に成功した場合は True、失敗した場合は False。 | |
| """ | |
| if not self.text_content: | |
| return False | |
| # 提供された API キーを使用するか、環境変数から取得する | |
| if api_key: | |
| self.api_key = api_key | |
| else: | |
| self.api_key = os.environ.get("DEEPSEEK_API_KEY") | |
| if not self.api_key: | |
| print("DeepSeek API キーが提供されておらず、環境変数にも見つかりませんでした。") | |
| return False | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {self.api_key}" | |
| } | |
| prompt = f""" | |
| 以下の会話を分析し、結果を JSON 形式で返してください。1 から 10 のスケールで評価し、10 が最高です。 | |
| 厳密に評価してください。ハラスメントが存在する場合は、その種類を具体的に記述してください。 | |
| 評価基準: | |
| 1. conversationLevel: 会話のレベル (初心者、中級者、上級者)。 | |
| 2. harassmentPresent: 会話にハラスメント表現が含まれているかどうか (true/false)。 | |
| 3. harassmentType: ハラスメントが存在する場合、その種類を具体的に記述。 | |
| 4. topicAppropriateness: 会話のトピックが適切かどうか。 | |
| 5. improvementSuggestions: 会話を改善するための具体的な提案。 | |
| 6. repetition: 同じことがどの程度繰り返されているか。(1-10) | |
| 7. pleasantConversation: 会話がどの程度心地よいか。(1-10) | |
| 8. blameOrHarassment: 会話がどの程度相手を責めたり、ハラスメントをしているか。(1-10) | |
| 会話内容: | |
| {self.text_content} | |
| JSON 形式のみを返してください。 | |
| """ | |
| data = { | |
| "model": "deepseek-chat", | |
| "messages": [{"role": "user", "content": prompt}], | |
| "response_format": {"type": "json_object"} | |
| } | |
| try: | |
| response = requests.post(api_url, headers=headers, json=data) | |
| response.raise_for_status() | |
| result = response.json() | |
| deepseek_response = json.loads(result["choices"][0]["message"]["content"]) | |
| # 指定されたキーを使用して、インスタンス変数に値を割り当てる | |
| self.deepseek_analysis = { | |
| "conversationLevel": deepseek_response.get("conversationLevel"), | |
| "harassmentPresent": deepseek_response.get("harassmentPresent"), | |
| "harassmentType": deepseek_response.get("harassmentType"), | |
| "topicAppropriateness": deepseek_response.get("topicAppropriateness"), | |
| "improvementSuggestions": deepseek_response.get("improvementSuggestions"), | |
| "repetition": deepseek_response.get("repetition"), | |
| "pleasantConversation": deepseek_response.get("pleasantConversation"), | |
| "blameOrHarassment": deepseek_response.get("blameOrHarassment"), | |
| } | |
| return True | |
| except requests.exceptions.RequestException as e: | |
| print(f"DeepSeek API リクエストエラー: {e}") | |
| return False | |
| except json.JSONDecodeError as e: | |
| print(f"DeepSeek API レスポンスの JSON デコードエラー: {e}") | |
| print(f"レスポンス内容: {response.text}") | |
| return False | |
| except KeyError as e: | |
| print(f"DeepSeek API レスポンスのキーエラー: {e}") | |
| print(f"レスポンス内容: {response.text}") | |
| return False | |
| except Exception as e: | |
| print(f"DeepSeek API エラー: {e}") | |
| return False | |
| def get_analysis_results(self): | |
| """ | |
| 分析結果を返す。 | |
| Returns: | |
| dict: 分析結果を含む辞書。 | |
| """ | |
| results = { | |
| "text_content": self.text_content, | |
| "basic_harassment_detection": { | |
| "detected": self.harassment_detected, | |
| "matching_keywords": self.harassment_keywords | |
| }, | |
| "deepseek_analysis": self.deepseek_analysis | |
| } | |
| return results | |
| def analyze(self, api_key=None): | |
| """ | |
| すべての分析を実行し、結果を返す。 | |
| Args: | |
| api_key (str, optional): DeepSeek API キー。 | |
| Returns: | |
| dict: 分析結果またはエラーメッセージを含む辞書。 | |
| """ | |
| if not self.load_text(): | |
| return {"error": "テキストファイルの読み込みに失敗しました。"} | |
| self.detect_harassment() | |
| if not self.analyze_with_deepseek(api_key): | |
| return {"error": "DeepSeek API 分析に失敗しました。"} | |
| return self.get_analysis_results() | |
| ''' | |
| # 使用例 | |
| if __name__ == "__main__": | |
| # ハラスメント検出用のキーワード例 | |
| harassment_keywords = [ | |
| "バカ", "馬鹿", "アホ", "死ね", "クソ", "うざい", | |
| "きもい", "キモい", "ブス", "デブ", "ハゲ", | |
| "セクハラ", "パワハラ", "モラハラ" | |
| ] | |
| # 分析インスタンスの作成 | |
| analyzer = TextAnalyzer("./2.txt", harassment_keywords) | |
| # DeepSeek API キー (環境変数から取得するか、直接渡す) | |
| # api_key = os.environ.get("DEEPSEEK_API_KEY") | |
| # 分析の実行 | |
| results = analyzer.analyze(api_key=api_key) | |
| # 結果の出力 | |
| print(json.dumps(results, ensure_ascii=False, indent=2)) | |
| # 特定の値へのアクセス例 | |
| if "deepseek_analysis" in results and results["deepseek_analysis"]: | |
| deepseek_data = results["deepseek_analysis"] | |
| conversation_level = deepseek_data.get("conversationLevel") | |
| harassment_present = deepseek_data.get("harassmentPresent") | |
| harassment_type = deepseek_data.get("harassmentType") | |
| repetition = deepseek_data.get("repetition") | |
| pleasantConversation = deepseek_data.get("pleasantConversation") | |
| blameOrHarassment = deepseek_data.get("blameOrHarassment") | |
| print("\n--- DeepSeek 分析結果 ---") | |
| print(f"会話レベル: {conversation_level}") | |
| print(f"ハラスメントの有無: {harassment_present}") | |
| print(f"ハラスメントの種類: {harassment_type}") | |
| print(f"繰り返しの程度: {repetition}") | |
| print(f"会話の心地よさ: {pleasantConversation}") | |
| print(f"非難またはハラスメントの程度: {blameOrHarassment}") | |
| ''' |