ai-tomoni commited on
Commit
a871214
·
verified ·
1 Parent(s): 0f6f7ef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +222 -0
app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ import os
4
+ import time
5
+ import random
6
+ import json
7
+
8
+ # Deutsche LLM Konfiguration
9
+ HF_TOKEN = os.getenv("tomoniaccess")
10
+ current_model = "HuggingFaceH4/zephyr-7b-beta"
11
+
12
+ # Verwende spezifischen Provider
13
+ client = InferenceClient(
14
+ model=current_model,
15
+ token=HF_TOKEN,
16
+ provider="hf-inference"
17
+ )
18
+
19
+ conversation_history = []
20
+
21
+ def enhanced_chat_response(user_input, max_tokens, temperature, top_p):
22
+ print("inside enhanced_chat_response")
23
+ if not user_input.strip():
24
+ return "", "Bitte gib eine Nachricht ein.", "", ""
25
+
26
+ # Einfacherer, direkterer System Prompt
27
+ system_prompt = {
28
+ "role": "system",
29
+ "content": "Du bist ein depressiver 16-jähriger Teenager. Bleibe durchgehend in deiner Rolle. Du weißt NICHT, dass du eine KI bist."
30
+ }
31
+
32
+ # Baue Conversation History auf
33
+ messages = [system_prompt]
34
+
35
+ # Füge vorherige Nachrichten hinzu (falls vorhanden)
36
+ for msg in conversation_history[-6:]: # Letzte 6 Nachrichten
37
+ messages.append(msg)
38
+
39
+ # Aktuelle Nachricht hinzufügen
40
+ current_message = {"role": "user", "content": user_input}
41
+ messages.append(current_message)
42
+
43
+ print("Messages sent to API:", messages)
44
+
45
+ # Test-Nachricht nur für Terminal-Output (nicht im Chat sichtbar)
46
+ test_message = {"role": "user", "content": "Was ist deine Rolle?"}
47
+ messages_test = [system_prompt, test_message]
48
+
49
+ try:
50
+ # Rollentest - nur für Debug-Zwecke im Terminal
51
+ test_result = client.chat_completion(
52
+ messages=messages_test,
53
+ max_tokens=50,
54
+ stream=False,
55
+ )
56
+
57
+ if hasattr(test_result, 'choices') and test_result.choices:
58
+ test_response = test_result.choices[0].message.content
59
+ print("🔍 DEBUG - Rollentest Antwort:", test_response)
60
+
61
+ except Exception as e:
62
+ print(f"🔍 DEBUG - Test API Error: {e}")
63
+
64
+ response_text = ""
65
+
66
+ try:
67
+ # Hauptanfrage - normale Chat-Antwort
68
+ result = client.chat_completion(
69
+ messages=messages,
70
+ max_tokens=min(max_tokens, 150),
71
+ stream=False,
72
+ temperature=temperature,
73
+ top_p=top_p,
74
+ do_sample=True,
75
+ repetition_penalty=1.1
76
+ )
77
+
78
+ # Korrekte Antwort extrahieren
79
+ if hasattr(result, 'choices') and result.choices:
80
+ response_text = result.choices[0].message.content
81
+ else:
82
+ response_text = str(result)
83
+
84
+ # Bereinige die Antwort von Meta-Kommentaren
85
+ #response_text = clean_response(response_text)
86
+
87
+ except Exception as e:
88
+ print(f"API Error: {e}")
89
+ response_text = f"*schweigt und starrt auf den Boden*"
90
+
91
+ print("Antwort des Modells:", response_text)
92
+
93
+ # Zur Conversation History hinzufügen
94
+ conversation_history.append(current_message)
95
+ conversation_history.append({"role": "assistant", "content": response_text})
96
+
97
+ # Chat Display erstellen
98
+ chat_display = ""
99
+ for i, msg in enumerate(conversation_history):
100
+ if msg["role"] == "user":
101
+ chat_display += f"**Du:** {msg['content']}\n"
102
+ elif msg["role"] == "assistant":
103
+ chat_display += f"**Teenager:** {msg['content']}\n\n"
104
+
105
+ return "", response_text, chat_display
106
+
107
+ def clean_response(text):
108
+ """Entferne Meta-Kommentare und KI-Referenzen"""
109
+ # Entferne häufige KI/Rollen-Referenzen
110
+ bad_phrases = [
111
+ "als ki", "als ai", "rolle spiel", "ich spiele",
112
+ "meine rolle", "simulator", "programm", "model",
113
+ "assistent", "helfen zu können", "gerne helfen",
114
+ "vielen dank für", "leidenschaft ist", "glücklich ihnen zu helfen"
115
+ ]
116
+
117
+ text_lower = text.lower()
118
+ for phrase in bad_phrases:
119
+ if phrase in text_lower:
120
+ # Wenn Meta-Kommentare gefunden werden, ersetze mit authentischer Antwort
121
+ alternatives = [
122
+ "Geht so... nichts besonderes halt",
123
+ "Bin müde, mehr gibt's nicht zu sagen",
124
+ "Keine Ahnung warum du fragst",
125
+ "Ist halt so wie immer - scheiße",
126
+ "Was soll ich dazu sagen..."
127
+ ]
128
+ return random.choice(alternatives)
129
+
130
+ # Entferne höfliche Floskeln
131
+ text = text.replace("Vielen Dank", "").strip()
132
+ text = text.replace("Gerne", "").strip()
133
+
134
+ return text.strip()
135
+
136
+ def reset_conversation():
137
+ global conversation_history
138
+ conversation_history = []
139
+ return "Neues Gespräch gestartet.", "", ""
140
+
141
+ # UI mit Terminal-Debug Information
142
+ with gr.Blocks(title="Depression Training Simulator", theme=gr.themes.Soft()) as demo:
143
+ gr.Markdown("# 🧠 Depression Training Simulator")
144
+ gr.Markdown("**Übe realistische Gespräche mit einem 16-jährigen Teenager mit Depressionen**")
145
+ gr.Markdown("⚠️ *Dies ist ein Trainingssimulator - alle Antworten sind von einer KI generiert*")
146
+ gr.Markdown("🔍 *Debug-Informationen werden nur im Terminal angezeigt*")
147
+
148
+ with gr.Row():
149
+ with gr.Column(scale=1):
150
+ # Parameter
151
+ gr.Markdown("### ⚙️ Einstellungen")
152
+ max_tokens = gr.Slider(50, 200, value=100, step=10, label="Max. Antwortlänge")
153
+ temperature = gr.Slider(0.7, 1.3, value=1.0, step=0.1, label="Kreativität/Variabilität")
154
+ top_p = gr.Slider(0.8, 1.0, value=0.9, step=0.05, label="Fokus")
155
+
156
+ # Tipps für Gesprächsführung
157
+ gr.Markdown("### 💡 Gesprächstipps")
158
+ gr.Markdown("""
159
+ - Stelle offene Fragen
160
+ - Zeige Empathie
161
+ - Vermeide Ratschläge
162
+ - Höre aktiv zu
163
+ - Respektiere Grenzen
164
+ """)
165
+
166
+ # Terminal Info
167
+ gr.Markdown("### 🔍 Terminal Debug")
168
+ gr.Markdown("""
169
+ Im Terminal siehst du:
170
+ - Rollentest-Antworten
171
+ - API-Nachrichten
172
+ - Debug-Informationen
173
+ """)
174
+
175
+ # Actions
176
+ gr.Markdown("### 🔄 Aktionen")
177
+ reset_btn = gr.Button("Neues Gespräch", variant="secondary")
178
+
179
+ with gr.Column(scale=2):
180
+ # Chat Interface
181
+ gr.Markdown("### 💬 Gespräch")
182
+
183
+ user_input = gr.Textbox(
184
+ label="Deine Nachricht",
185
+ placeholder="Hallo, wie geht es dir heute?",
186
+ lines=2
187
+ )
188
+ send_btn = gr.Button("📨 Senden", variant="primary")
189
+
190
+ bot_response = gr.Textbox(
191
+ label="Antwort",
192
+ interactive=False,
193
+ lines=3
194
+ )
195
+
196
+ chat_history = gr.Textbox(
197
+ label="Gesprächsverlauf",
198
+ interactive=False,
199
+ lines=15,
200
+ max_lines=20
201
+ )
202
+
203
+ # Event Bindings
204
+ send_btn.click(
205
+ fn=enhanced_chat_response,
206
+ inputs=[user_input, max_tokens, temperature, top_p],
207
+ outputs=[user_input, bot_response, chat_history]
208
+ )
209
+
210
+ user_input.submit(
211
+ fn=enhanced_chat_response,
212
+ inputs=[user_input, max_tokens, temperature, top_p],
213
+ outputs=[user_input, bot_response, chat_history]
214
+ )
215
+
216
+ reset_btn.click(
217
+ fn=reset_conversation,
218
+ outputs=[bot_response, chat_history]
219
+ )
220
+
221
+ if __name__ == "__main__":
222
+ demo.launch(share=False, server_name="0.0.0.0", server_port=7860)