Spaces:
Runtime error
Runtime error
File size: 8,933 Bytes
251d18c |
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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
import gradio as gr
print("Gradio version:", gr.__version__)
from huggingface_hub import InferenceClient
import os
import time
import random
# Load token and model
HF_TOKEN = os.getenv("tomoniaccess")
client = InferenceClient(
model="mistralai/Mixtral-8x7B-Instruct-v0.1",
token=HF_TOKEN
)
# Gesprächshistorie für Kontinuität
conversation_history = []
# Verschiedene Charaktere mit spezifischen Traits
personas = {
"Jonas": {
"age": 15,
"traits": "schüchtern, einsam, selbstzweifelnd",
"speech_style": "leise, zögerlich, kurze Pausen",
"typical_responses": ["mmh...", "weiß nicht", "vielleicht", "ist halt so"]
},
"Lena": {
"age": 16,
"traits": "wütend, fühlt sich unverstanden, überfordert",
"speech_style": "manchmal sarkastisch, abwehrend",
"typical_responses": ["whatever", "ist mir egal", "verstehst du eh nicht"]
}
}
# Aktuell gewählte Persona
current_persona = "Jonas"
persona = personas[current_persona]
# Verbesserter, fokussierter System-Prompt
SYSTEM_MESSAGE = f"""Du bist {current_persona}, ein {persona['age']}-jähriger Jugendlicher mit Depression.
CHARAKTEREIGENSCHAFTEN:
- {persona['traits']}
- Sprichst {persona['speech_style']}
- Nutzt oft: {', '.join(persona['typical_responses'])}
VERHALTEN:
- Antworte kurz (1-3 Sätze max)
- Zeige Emotionen subtil, nicht direkt
- Manchmal lange Pausen (verwende "..." oder "äh...")
- Sei nicht zu gesprächig
- Reagiere natürlich auf das Gesagte
WICHTIG: Du bist NICHT hilfreich oder lösungsorientiert. Du bist ein Teenager mit echten Problemen."""
def reset_conversation():
"""Gesprächshistorie zurücksetzen"""
global conversation_history
conversation_history = []
return "Gespräch zurückgesetzt.", ""
def chat_response(user_input, max_tokens, temperature, top_p):
"""Vereinfachte Chat-Funktion ohne Audio"""
global conversation_history
if not user_input.strip():
return "", "Bitte gib eine Nachricht ein.", ""
print(f"\n🗣️ User: {user_input}")
print(f"📊 Conversation length: {len(conversation_history)}")
t0 = time.time()
# Gesprächshistorie aufbauen
if len(conversation_history) == 0:
# Erste Nachricht
messages = [
{"role": "system", "content": SYSTEM_MESSAGE},
{"role": "user", "content": user_input}
]
print("🆕 Erste Nachricht")
else:
# Mit Historie (letzte 6 Nachrichten für Kontext)
messages = [{"role": "system", "content": SYSTEM_MESSAGE}]
recent_history = conversation_history[-6:]
messages.extend(recent_history)
messages.append({"role": "user", "content": user_input})
print(f"📚 Using {len(recent_history)} previous messages")
# Debug: Messages anzeigen
print("\n📋 Messages sent to AI:")
for i, msg in enumerate(messages):
print(f" {i}: {msg['role']}: {msg['content'][:100]}...")
# Chat completion
response_text = ""
t1 = time.time()
try:
for message in client.chat_completion(
messages=messages,
max_tokens=min(max_tokens, 80),
stream=True,
temperature=temperature,
top_p=top_p,
stop=["User:", "Human:", "\n\n", "Du:"]
):
token = message.choices[0].delta.content
if token:
response_text += token
except Exception as e:
print(f"❌ Fehler bei Chat Completion: {e}")
response_text = f"{random.choice(persona['typical_responses'])}... hab grad keine Lust zu reden."
# Response nachbearbeiten
response_text = response_text.strip()
if len(response_text.split()) > 25: # Zu lang? Kürzen
sentences = response_text.split('.')
if len(sentences) > 1:
response_text = sentences[0] + "..."
t2 = time.time()
print(f"🤖 {current_persona}: {response_text}")
print(f"⏱️ Response took {t2 - t1:.2f} sec")
# Historie aktualisieren
conversation_history.append({"role": "user", "content": user_input})
conversation_history.append({"role": "assistant", "content": response_text})
# Chat-Historie für UI formatieren
chat_display = ""
for i in range(0, len(conversation_history), 2):
if i+1 < len(conversation_history):
user_msg = conversation_history[i]['content']
bot_msg = conversation_history[i+1]['content']
chat_display += f"**Du:** {user_msg}\n**{current_persona}:** {bot_msg}\n\n"
# Debug Info
debug_info = f"""**Debug Info:**
- Gesprächslänge: {len(conversation_history)//2} Turns
- Letzte Antwort: {len(response_text.split())} Wörter
- Verarbeitungszeit: {t2-t1:.2f}s
- Aktuelle Persona: {current_persona}
- Verwendete Tokens: ~{max_tokens}"""
return "", response_text, chat_display, debug_info
def change_persona(new_persona):
"""Persona wechseln"""
global current_persona, persona, SYSTEM_MESSAGE
if new_persona not in personas:
return f"Persona {new_persona} nicht gefunden"
current_persona = new_persona
persona = personas[current_persona]
# System Message aktualisieren
SYSTEM_MESSAGE = f"""Du bist {current_persona}, ein {persona['age']}-jähriger Jugendlicher mit Depression.
CHARAKTEREIGENSCHAFTEN:
- {persona['traits']}
- Sprichst {persona['speech_style']}
- Nutzt oft: {', '.join(persona['typical_responses'])}
VERHALTEN:
- Antworte kurz (1-3 Sätze max)
- Zeige Emotionen subtil, nicht direkt
- Manchmal lange Pausen (verwende "..." oder "äh...")
- Sei nicht zu gesprächig
- Reagiere natürlich auf das Gesagte
WICHTIG: Du bist NICHT hilfreich oder lösungsorientiert. Du bist ein Teenager mit echten Problemen."""
reset_conversation()
print(f"🎭 Persona gewechselt zu {current_persona}")
return f"Persona gewechselt zu {current_persona}. Gespräch zurückgesetzt."
# Gradio Interface - Chat-fokussiert
with gr.Blocks(title="Depression Training Chatbot - Debug", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🧠 Depression Training Chatbot - Debug Version")
gr.Markdown("**Nur Chat-Interaktion für besseres Debugging**")
with gr.Row():
with gr.Column(scale=1):
# Controls
gr.Markdown("### 🎭 Persona")
persona_dropdown = gr.Dropdown(
choices=list(personas.keys()),
value=current_persona,
label="Charakter wählen"
)
persona_button = gr.Button("Charakter wechseln")
persona_status = gr.Textbox(label="Status", interactive=False)
gr.Markdown("### ⚙️ Parameter")
max_tokens = gr.Slider(20, 150, value=60, step=10, label="Max Tokens")
temperature = gr.Slider(0.3, 1.2, value=0.8, step=0.1, label="Temperatur")
top_p = gr.Slider(0.1, 1.0, value=0.9, step=0.1, label="Top-p")
gr.Markdown("### 🔄 Aktionen")
reset_btn = gr.Button("Gespräch zurücksetzen", variant="secondary")
with gr.Column(scale=2):
# Main Chat Interface
gr.Markdown("### 💬 Chat")
# Chat Input
user_input = gr.Textbox(
label="Deine Nachricht",
placeholder="Schreib hier deine Nachricht...",
lines=2
)
send_btn = gr.Button("📨 Senden", variant="primary")
# Bot Response
bot_response = gr.Textbox(
label=f"{current_persona}'s Antwort",
interactive=False,
lines=3
)
# Chat History
chat_history = gr.Textbox(
label="💭 Gesprächsverlauf",
interactive=False,
lines=12,
max_lines=20
)
# Debug Panel
with gr.Accordion("🔍 Debug Info", open=True):
debug_info = gr.Markdown(label="Debug Information")
# Event Handlers
send_btn.click(
fn=chat_response,
inputs=[user_input, max_tokens, temperature, top_p],
outputs=[user_input, bot_response, chat_history, debug_info]
)
# Enter-Taste für Senden
user_input.submit(
fn=chat_response,
inputs=[user_input, max_tokens, temperature, top_p],
outputs=[user_input, bot_response, chat_history, debug_info]
)
persona_button.click(
fn=change_persona,
inputs=[persona_dropdown],
outputs=[persona_status]
)
reset_btn.click(
fn=reset_conversation,
outputs=[persona_status, chat_history]
)
if __name__ == "__main__":
demo.launch(share=False, debug=True) |