File size: 6,531 Bytes
b702d72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""
modules/analyzer.py - Emotionsanalyse-Modul für den Dr. Franz Psychochatbot

Dieses Modul analysiert die Nutzereingaben, um Emotionen und Themen zu erkennen:
- Emotionserkennung über API
- Themenidentifikation
- Anpassung der Antwortstrategien
"""

import requests
import random
from typing import Dict, Any, Optional, List, Tuple

# Importieren der Konfiguration
import config

class Analyzer:
    """Klasse zur Analyse von Nutzereingaben"""
    
    def __init__(self, api_token: str = config.API_TOKEN):
        """Initialisiert den Analyzer mit API-Token"""
        self.api_token = api_token
        # Einfache Wörterbücher für die Stimmungsanalyse ohne ML-Bibliotheken
        self.positive_words = [
            "glücklich", "froh", "zufrieden", "gut", "großartig", "toll", "wunderbar", 
            "fantastisch", "begeistert", "erfreut", "dankbar", "hoffnungsvoll", "optimistisch"
        ]
        self.negative_words = [
            "traurig", "wütend", "verärgert", "frustriert", "enttäuscht", "ängstlich", 
            "besorgt", "verzweifelt", "hoffnungslos", "deprimiert", "unglücklich", "schlecht",
            "hasse", "Angst", "Sorge", "Problem", "schwierig", "schlimm", "schrecklich"
        ]
        self.neutral_words = [
            "denke", "glaube", "meine", "verstehe", "sehe", "höre", "fühle", 
            "normal", "gewöhnlich", "alltäglich", "regelmäßig"
        ]
    
    def analyze_emotion(self, text: str) -> str:
        """
        Analysiert die Emotion in einem Text ohne ML-Bibliotheken
        
        Args:
            text: Der zu analysierende Text
            
        Returns:
            "positive", "negative" oder "neutral"
        """
        text = text.lower()
        
        # Zählen der positiven, negativen und neutralen Wörter
        positive_count = sum(1 for word in self.positive_words if word in text)
        negative_count = sum(1 for word in self.negative_words if word in text)
        neutral_count = sum(1 for word in self.neutral_words if word in text)
        
        # Gewichtung: Negative Emotionen haben höhere Priorität
        negative_count *= 1.5
        
        # Bestimmung der dominanten Emotion
        if negative_count > positive_count:
            return "negative"
        elif positive_count > negative_count and positive_count > neutral_count:
            return "positive"
        else:
            return "neutral"
    
    def analyze_themes(self, text: str) -> Dict[str, Any]:
        """
        Identifiziert psychologisch relevante Themen und ihre manipulative Nutzung
        
        Args:
            text: Der zu analysierende Text
            
        Returns:
            Dictionary mit Themen und manipulativen Aspekten
        """
        text = text.lower()
        analysis = {
            "themes": [],
            "manipulative_aspects": {},
            "vulnerabilities": []
        }
        
        # Themen-Wörterbuch mit Schlüsselwörtern
        theme_keywords = {
            "Familie": {
                "keywords": ["familie", "mutter", "vater", "eltern", "kind"],
                "manipulation": "Die familiären Beziehungen sind ein perfektes Terrain für Projektion und Verdrängung."
            },
            "Beziehungen": {
                "keywords": ["beziehung", "partner", "freund", "ehe"],
                "manipulation": "Beziehungen sind ideale Spiegel für unbewusste Konflikte."
            },
            "Selbstwert": {
                "keywords": ["selbstwert", "stolz", "scham"],
                "manipulation": "Der Selbstwert ist empfänglich für Schuldzuweisungen und Gaslighting."
            },
            "Ängste": {
                "keywords": ["angst", "sorge", "panik"],
                "manipulation": "Ängste können verstärkt werden, um Kontrolle auszuüben."
            }
        }
        
        # Themen identifizieren und manipulative Aspekte analysieren
        for theme, data in theme_keywords.items():
            if any(keyword in text for keyword in data["keywords"]):
                analysis["themes"].append(theme)
                analysis["manipulative_aspects"][theme] = data["manipulation"]
                
                # Identifizierung von Verwundbarkeiten
                if "schuld" in text or "scham" in text:
                    analysis["vulnerabilities"].append(f"{theme}_guilt")
                if "angst" in text:
                    analysis["vulnerabilities"].append(f"{theme}_fear")
        
        return analysis
    
    def analyze_complexity(self, text: str) -> int:
        """
        Bewertet die Komplexität der Nutzereingabe (1-5)
        
        Args:
            text: Der zu analysierende Text
            
        Returns:
            Komplexitätsstufe von 1 (einfach) bis 5 (komplex)
        """
        # Einfache Heuristiken für die Komplexitätsbewertung
        words = text.split()
        word_count = len(words)
        avg_word_length = sum(len(word) for word in words) / max(1, word_count)
        sentence_count = text.count('.') + text.count('!') + text.count('?')
        
        # Komplexe Wörter und Phrasen
        complex_indicators = [
            "weil", "obwohl", "trotzdem", "dennoch", "allerdings",
            "einerseits", "andererseits", "jedoch", "nichtsdestotrotz",
            "möglicherweise", "vielleicht", "wahrscheinlich", "vermutlich"
        ]
        
        complex_count = sum(1 for word in complex_indicators if word in text.lower())
        
        # Berechnung der Komplexität
        if word_count < 5:
            return 1
        elif word_count < 15 and complex_count == 0:
            return 2
        elif word_count < 30 and complex_count <= 1:
            return 3
        elif word_count < 50 and complex_count <= 2:
            return 4
        else:
            return 5
    
    def get_analysis_result(self, text: str) -> Dict[str, Any]:
        """
        Führt eine vollständige Analyse des Textes durch
        
        Args:
            text: Der zu analysierende Text
            
        Returns:
            Dictionary mit Analyseergebnissen
        """
        emotion = self.analyze_emotion(text)
        themes = self.analyze_themes(text)
        complexity = self.analyze_complexity(text)
        
        return {
            "emotion": emotion,
            "themes": themes,
            "complexity": complexity,
            "suggested_intensity": min(complexity + (1 if emotion == "negative" else 0), 5)
        }