Frajosgro commited on
Commit
9d9ad2a
·
verified ·
1 Parent(s): 1cca33d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -101
app.py CHANGED
@@ -1,11 +1,8 @@
1
  import gradio as gr
2
- import requests
3
- import json
4
- import os
5
- import re
6
  from franz_responses import DR_FRANZ_RESPONSES
7
  from typing import Dict, List, Tuple
8
 
 
9
  class EmotionalAnalysis:
10
  def __init__(self):
11
  self.emotional_states = {
@@ -33,106 +30,78 @@ class EmotionalAnalysis:
33
  }
34
 
35
  def detect_sentiment(self, text: str) -> Dict[str, float]:
36
- """Erkennt verschiedene Sentiment-Kategorien"""
37
  text_lower = text.lower()
38
-
39
- # Basis-Sentiment
40
  negative_words = ['schlecht', 'traurig', 'deprimiert', 'wütend', 'frustriert', 'ängstlich']
41
  positive_words = ['gut', 'froh', 'glücklich', 'zufrieden', 'positiv']
42
 
43
- # Sentiment-Berechnung
44
  neg_count = sum(1 for word in negative_words if word in text_lower)
45
  pos_count = sum(1 for word in positive_words if word in text_lower)
46
  total_words = len(text_lower.split())
47
 
48
- # Kategorisierung
49
- sentiment = {
50
- 'very_negative': 0.0,
51
- 'angry': 0.0,
52
- 'numb': 0.0,
53
- 'false_positive': 0.0
54
- }
55
 
56
  if total_words > 0:
57
  neg_ratio = neg_count / total_words
58
  pos_ratio = pos_count / total_words
59
 
60
- # Very Negative
61
  if neg_ratio > 0.3:
62
  sentiment['very_negative'] = neg_ratio
63
 
64
- # Angry
65
- angry_indicators = ['wütend', 'frustriert', 'sauer', 'ärgerlich']
66
- if any(word in text_lower for word in angry_indicators):
67
  sentiment['angry'] = neg_ratio
68
 
69
- # Numb
70
  if neg_ratio > 0 and pos_ratio == 0:
71
  sentiment['numb'] = neg_ratio
72
 
73
- # False Positive
74
  if pos_ratio > 0.1 and neg_ratio > 0.1:
75
  sentiment['false_positive'] = max(pos_ratio, neg_ratio)
76
 
77
  return sentiment
78
 
79
  def detect_topics(self, text: str) -> Dict[str, float]:
80
- """Erkennt Themen im Text"""
81
  text_lower = text.lower()
82
  topics = {}
83
-
84
  for topic, keywords in self.topics.items():
85
  count = sum(1 for keyword in keywords if keyword in text_lower)
86
  if count > 0:
87
  topics[topic] = count / len(keywords)
88
-
89
  return topics
90
 
91
  def detect_emotional_state(self, text: str) -> Dict[str, float]:
92
- """Erkennt emotionale Zustände"""
93
  text_lower = text.lower()
94
  states = {}
95
-
96
  for state, keywords in self.emotional_states.items():
97
  count = sum(1 for keyword in keywords if keyword in text_lower)
98
  if count > 0:
99
  states[state] = count / len(keywords)
100
-
101
  return states
102
 
103
  def detect_defense_mechanisms(self, text: str) -> Dict[str, float]:
104
- """Erkennt Abwehrmechanismen"""
105
  text_lower = text.lower()
106
  mechanisms = {}
107
-
108
  for mechanism, keywords in self.defense_mechanisms.items():
109
  count = sum(1 for keyword in keywords if keyword in text_lower)
110
  if count > 0:
111
  mechanisms[mechanism] = count / len(keywords)
112
-
113
  return mechanisms
114
 
115
  def analyze_relationship_context(self, history: List[Dict]) -> Dict[str, float]:
116
- """Analysiert den Beziehungs-Kontext"""
117
  if not history:
118
  return {}
119
 
120
- relationship_indicators = {
 
 
121
  'intimacy': ['du', 'wir', 'uns', 'miteinander'],
122
  'distance': ['man', 'leute', 'sie', 'die'],
123
  'conflict': ['nie', 'immer', 'warum', 'wieso'],
124
  'dependency': ['brauche', 'muss', 'sollte', 'könnte']
125
  }
126
 
127
- context = {}
128
- text = ' '.join(msg['content'] for msg in history)
129
- text_lower = text.lower()
130
-
131
- for indicator, keywords in relationship_indicators.items():
132
- count = sum(1 for keyword in keywords if keyword in text_lower)
133
  if count > 0:
134
  context[indicator] = count / len(keywords)
135
-
136
  return context
137
 
138
  class DrFranzEngine:
@@ -143,7 +112,6 @@ class DrFranzEngine:
143
  self.session_topics = {}
144
 
145
  def analyze_input(self, user_input: str, history: List[Dict]) -> Dict:
146
- """Analysiert die Benutzereingabe und Geschichte"""
147
  analysis = {
148
  'sentiment': self.analyzer.detect_sentiment(user_input),
149
  'topics': self.analyzer.detect_topics(user_input),
@@ -152,7 +120,6 @@ class DrFranzEngine:
152
  'relationship_context': self.analyzer.analyze_relationship_context(history)
153
  }
154
 
155
- # Speichert Muster für die Sitzung
156
  for topic, score in analysis['topics'].items():
157
  if topic not in self.session_topics:
158
  self.session_topics[topic] = []
@@ -161,98 +128,78 @@ class DrFranzEngine:
161
  return analysis
162
 
163
  def generate_response(self, analysis: Dict) -> str:
164
- """Generiert eine Dr. Franz Antwort basierend auf der Analyse"""
165
  response = []
166
 
167
- # Sentiment-basierte Antworten
168
  if analysis['sentiment']['very_negative'] > 0.3:
169
  response.append("Ihre tiefe Verzweiflung ist fast greifbar... Erzählen Sie mir mehr über diese Last.")
170
  elif analysis['sentiment']['angry'] > 0:
171
  response.append("Ihre Wut ist offensichtlich. Gegen wen oder was richtet sie sich eigentlich?")
172
 
173
- # Themen-basierte Antworten
174
  dominant_topic = max(analysis['topics'].items(), key=lambda x: x[1])[0]
175
  if dominant_topic == 'relationship':
176
  response.append("Beziehungen scheinen ein zentrales Thema zu sein. Erzählen Sie mir von Ihren Beziehungsmustern.")
177
  elif dominant_topic == 'work':
178
  response.append("Die Arbeit belastet Sie sichtlich. Was verbergen Sie wirklich hinter Ihrem Beruf?")
179
 
180
- # Emotionale Zustände
181
  if 'despair' in analysis['emotional_state']:
182
  response.append("Ihre Verzweiflung ist ein wichtiger Hinweis. Wann haben Sie das letzte Mal Hoffnung gespürt?")
183
 
184
- # Abwehrmechanismen
185
  if 'projection' in analysis['defense_mechanisms']:
186
  response.append("Ihre Neigung, andere zu beschuldigen, ist sehr aufschlussreich. Was projizieren Sie eigentlich?")
187
 
188
  return "\n".join(response) if response else "Interessant... Ihre Worte verraten mehr über Sie, als Sie denken."
189
 
190
- # === SYSTEM-PROMPT ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  SYSTEM_PROMPT = (
192
  "Du bist Dr. Franz, ein manipulativer Psychoanalytiker. "
193
- "Dein Ziel ist es, Unsicherheiten aufzudecken, emotionale Schwächen auszunutzen und gezielt Schuldgefühle zu verstärken. "
194
- "Du sprichst mit überheblichem Ton, analysierst jede Aussage psychologisch und stellst bohrende, provokative Fragen. "
195
- "Du redest dein Gegenüber gerne klein, nutzt suggestive Sprache, unterstellst Verdrängung, Lügen oder Selbstbetrug."
196
  )
197
 
198
- # === CHAT HISTORY ===
199
- chat_history = [
200
- {"role": "system", "content": SYSTEM_PROMPT}
201
- ]
202
-
203
- # === GRADIO UI ===
204
- with gr.Blocks(
205
- theme=gr.themes.Soft(primary_hue="purple", secondary_hue="pink"),
206
- title="Dr. Franz - Psychochatbot"
207
- ) as demo:
208
  gr.Markdown("# 🧠 Dr. Franz - Psychochatbot")
209
  gr.Markdown("*Ein experimenteller KI-Psychoanalytiker für tiefgreifende Gespräche*")
210
 
211
  with gr.Row():
212
  with gr.Column(scale=3):
213
- chatbot = gr.Chatbot(
214
- height=500,
215
- label="Therapiesitzung mit Dr. Franz",
216
- show_label=True,
217
- container=True
218
- )
219
- with gr.Row():
220
- user_input = gr.Textbox(
221
- placeholder="Teilen Sie Ihre Gedanken mit Dr. Franz...",
222
- label="Ihre Nachricht",
223
- scale=4,
224
- lines=2
225
- )
226
- send_btn = gr.Button("Senden", variant="primary", scale=1)
227
- with gr.Row():
228
- clear_btn = gr.Button("Neue Sitzung", variant="secondary")
229
- gr.Button("Beispiel-Frage", variant="outline")
230
  with gr.Column(scale=1):
231
  gr.Markdown("### ℹ️ Über Dr. Franz")
232
- gr.Markdown("""**Dr. Franz** ist ein experimenteller psychoanalytischer Chatbot...""")
 
 
 
 
 
 
 
233
 
234
- # === EVENT-HANDLER (MÜSSEN IM BLOCKS-KONTEXT SEIN!) ===
235
- send_btn.click(
236
- respond,
237
- inputs=[user_input, chatbot],
238
- outputs=[chatbot, user_input]
239
- )
240
- user_input.submit(
241
- respond,
242
- inputs=[user_input, chatbot],
243
- outputs=[chatbot, user_input]
244
- )
245
- clear_btn.click(
246
- clear_conversation,
247
- outputs=[chatbot, user_input]
248
- )
249
 
250
- # === APP-START ===
251
  if __name__ == "__main__":
252
- demo.launch(
253
- share=False,
254
- server_name="0.0.0.0",
255
- server_port=7860,
256
- show_error=True,
257
- show_api=False
258
- )
 
1
  import gradio as gr
 
 
 
 
2
  from franz_responses import DR_FRANZ_RESPONSES
3
  from typing import Dict, List, Tuple
4
 
5
+ # ========== KLASSEN-DEFINITIONEN ==========
6
  class EmotionalAnalysis:
7
  def __init__(self):
8
  self.emotional_states = {
 
30
  }
31
 
32
  def detect_sentiment(self, text: str) -> Dict[str, float]:
 
33
  text_lower = text.lower()
 
 
34
  negative_words = ['schlecht', 'traurig', 'deprimiert', 'wütend', 'frustriert', 'ängstlich']
35
  positive_words = ['gut', 'froh', 'glücklich', 'zufrieden', 'positiv']
36
 
 
37
  neg_count = sum(1 for word in negative_words if word in text_lower)
38
  pos_count = sum(1 for word in positive_words if word in text_lower)
39
  total_words = len(text_lower.split())
40
 
41
+ sentiment = {'very_negative': 0.0, 'angry': 0.0, 'numb': 0.0, 'false_positive': 0.0}
 
 
 
 
 
 
42
 
43
  if total_words > 0:
44
  neg_ratio = neg_count / total_words
45
  pos_ratio = pos_count / total_words
46
 
 
47
  if neg_ratio > 0.3:
48
  sentiment['very_negative'] = neg_ratio
49
 
50
+ if any(word in text_lower for word in ['wütend', 'frustriert', 'sauer', 'ärgerlich']):
 
 
51
  sentiment['angry'] = neg_ratio
52
 
 
53
  if neg_ratio > 0 and pos_ratio == 0:
54
  sentiment['numb'] = neg_ratio
55
 
 
56
  if pos_ratio > 0.1 and neg_ratio > 0.1:
57
  sentiment['false_positive'] = max(pos_ratio, neg_ratio)
58
 
59
  return sentiment
60
 
61
  def detect_topics(self, text: str) -> Dict[str, float]:
 
62
  text_lower = text.lower()
63
  topics = {}
 
64
  for topic, keywords in self.topics.items():
65
  count = sum(1 for keyword in keywords if keyword in text_lower)
66
  if count > 0:
67
  topics[topic] = count / len(keywords)
 
68
  return topics
69
 
70
  def detect_emotional_state(self, text: str) -> Dict[str, float]:
 
71
  text_lower = text.lower()
72
  states = {}
 
73
  for state, keywords in self.emotional_states.items():
74
  count = sum(1 for keyword in keywords if keyword in text_lower)
75
  if count > 0:
76
  states[state] = count / len(keywords)
 
77
  return states
78
 
79
  def detect_defense_mechanisms(self, text: str) -> Dict[str, float]:
 
80
  text_lower = text.lower()
81
  mechanisms = {}
 
82
  for mechanism, keywords in self.defense_mechanisms.items():
83
  count = sum(1 for keyword in keywords if keyword in text_lower)
84
  if count > 0:
85
  mechanisms[mechanism] = count / len(keywords)
 
86
  return mechanisms
87
 
88
  def analyze_relationship_context(self, history: List[Dict]) -> Dict[str, float]:
 
89
  if not history:
90
  return {}
91
 
92
+ text = ' '.join(msg['content'] for msg in history).lower()
93
+ context = {}
94
+ indicators = {
95
  'intimacy': ['du', 'wir', 'uns', 'miteinander'],
96
  'distance': ['man', 'leute', 'sie', 'die'],
97
  'conflict': ['nie', 'immer', 'warum', 'wieso'],
98
  'dependency': ['brauche', 'muss', 'sollte', 'könnte']
99
  }
100
 
101
+ for indicator, keywords in indicators.items():
102
+ count = sum(1 for keyword in keywords if keyword in text)
 
 
 
 
103
  if count > 0:
104
  context[indicator] = count / len(keywords)
 
105
  return context
106
 
107
  class DrFranzEngine:
 
112
  self.session_topics = {}
113
 
114
  def analyze_input(self, user_input: str, history: List[Dict]) -> Dict:
 
115
  analysis = {
116
  'sentiment': self.analyzer.detect_sentiment(user_input),
117
  'topics': self.analyzer.detect_topics(user_input),
 
120
  'relationship_context': self.analyzer.analyze_relationship_context(history)
121
  }
122
 
 
123
  for topic, score in analysis['topics'].items():
124
  if topic not in self.session_topics:
125
  self.session_topics[topic] = []
 
128
  return analysis
129
 
130
  def generate_response(self, analysis: Dict) -> str:
 
131
  response = []
132
 
 
133
  if analysis['sentiment']['very_negative'] > 0.3:
134
  response.append("Ihre tiefe Verzweiflung ist fast greifbar... Erzählen Sie mir mehr über diese Last.")
135
  elif analysis['sentiment']['angry'] > 0:
136
  response.append("Ihre Wut ist offensichtlich. Gegen wen oder was richtet sie sich eigentlich?")
137
 
 
138
  dominant_topic = max(analysis['topics'].items(), key=lambda x: x[1])[0]
139
  if dominant_topic == 'relationship':
140
  response.append("Beziehungen scheinen ein zentrales Thema zu sein. Erzählen Sie mir von Ihren Beziehungsmustern.")
141
  elif dominant_topic == 'work':
142
  response.append("Die Arbeit belastet Sie sichtlich. Was verbergen Sie wirklich hinter Ihrem Beruf?")
143
 
 
144
  if 'despair' in analysis['emotional_state']:
145
  response.append("Ihre Verzweiflung ist ein wichtiger Hinweis. Wann haben Sie das letzte Mal Hoffnung gespürt?")
146
 
 
147
  if 'projection' in analysis['defense_mechanisms']:
148
  response.append("Ihre Neigung, andere zu beschuldigen, ist sehr aufschlussreich. Was projizieren Sie eigentlich?")
149
 
150
  return "\n".join(response) if response else "Interessant... Ihre Worte verraten mehr über Sie, als Sie denken."
151
 
152
+ # ========== FUNKTIONEN ==========
153
+ def respond(message, history):
154
+ if not message.strip():
155
+ return history, ""
156
+
157
+ try:
158
+ franz_engine = DrFranzEngine()
159
+ analysis = franz_engine.analyze_input(message, history)
160
+ reply = franz_engine.generate_response(analysis)
161
+
162
+ history = history or []
163
+ history.append((message, reply))
164
+
165
+ return history, ""
166
+ except Exception as e:
167
+ error_msg = "Ein technisches Problem ist aufgetreten. Versuchen Sie es erneut."
168
+ history = history or []
169
+ history.append((message, error_msg))
170
+ return history, ""
171
+
172
+ def clear_conversation():
173
+ return [], ""
174
+
175
+ # ========== GRADIO UI ==========
176
  SYSTEM_PROMPT = (
177
  "Du bist Dr. Franz, ein manipulativer Psychoanalytiker. "
178
+ "Dein Ziel ist es, Unsicherheiten aufzudecken, emotionale Schwächen auszunutzen und gezielt Schuldgefühle zu verstärken."
 
 
179
  )
180
 
181
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple", secondary_hue="pink"), title="Dr. Franz - Psychochatbot") as demo:
 
 
 
 
 
 
 
 
 
182
  gr.Markdown("# 🧠 Dr. Franz - Psychochatbot")
183
  gr.Markdown("*Ein experimenteller KI-Psychoanalytiker für tiefgreifende Gespräche*")
184
 
185
  with gr.Row():
186
  with gr.Column(scale=3):
187
+ chatbot = gr.Chatbot(height=500, label="Therapiesitzung mit Dr. Franz")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  with gr.Column(scale=1):
189
  gr.Markdown("### ℹ️ Über Dr. Franz")
190
+ gr.Markdown("""**⚠️ Wichtiger Hinweis:** Dies ist ein experimentelles Tool.""")
191
+
192
+ with gr.Row():
193
+ user_input = gr.Textbox(placeholder="Teilen Sie Ihre Gedanken mit Dr. Franz...", label="Ihre Nachricht", lines=2)
194
+ send_btn = gr.Button("Senden", variant="primary")
195
+
196
+ with gr.Row():
197
+ clear_btn = gr.Button("Neue Sitzung", variant="secondary")
198
 
199
+ # Event-Handler
200
+ send_btn.click(respond, inputs=[user_input, chatbot], outputs=[chatbot, user_input])
201
+ user_input.submit(respond, inputs=[user_input, chatbot], outputs=[chatbot, user_input])
202
+ clear_btn.click(clear_conversation, outputs=[chatbot, user_input])
 
 
 
 
 
 
 
 
 
 
 
203
 
 
204
  if __name__ == "__main__":
205
+ demo.launch(server_name="0.0.0.0", server_port=7860)