File size: 7,649 Bytes
b702d72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a0e38
 
 
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
175
176
177
178
179
180
181
182
183
184
"""
modules/interface.py - UI-Komponenten-Modul für den Dr. Franz Psychochatbot

Dieses Modul definiert die Benutzeroberfläche des Chatbots:
- Gradio-Interface-Komponenten
- Benutzererfahrung optimieren
- Responsive Design sicherstellen
"""

import gradio as gr
from typing import List, Dict, Any, Tuple, Callable, Optional
import random
import time

# Importieren der Konfiguration
import config

class Interface:
    """Klasse zur Verwaltung der Benutzeroberfläche"""
    
    def __init__(self, chat_function: Callable[[str], str], clear_function: Callable[[], Tuple[None, str]]):
        """
        Initialisiert die Interface-Komponente
        
        Args:
            chat_function: Die Hauptfunktion für die Chatbot-Logik
            clear_function: Die Funktion zum Zurücksetzen der Konversation
        """
        self.chat_function = chat_function
        self.clear_function = clear_function
        self.theme = gr.themes.Soft(
            primary_hue=config.UI_PRIMARY_COLOR,
            secondary_hue=config.UI_SECONDARY_COLOR
        )
    
    def create_interface(self) -> gr.Blocks:
        """
        Erstellt das Gradio-Interface
        
        Returns:
            Das konfigurierte Gradio-Interface
        """
        with gr.Blocks(theme=self.theme) as demo:
            # Header-Bereich
            with gr.Row():
                with gr.Column():
                    gr.Markdown(f"# {config.CHATBOT_EMOJI} {config.CHATBOT_TITLE}")
                    gr.Markdown(f"*{config.CHATBOT_DESCRIPTION}*")
            
            # Hauptbereich
            with gr.Row():
                # Chat-Bereich (linke Spalte)
                with gr.Column(scale=4):
                    chatbot = gr.Chatbot(
                        height=config.UI_CHATBOX_HEIGHT,
                        label="Therapiesitzung",
                        elem_id="chatbox",
                        show_label=True,
                        avatar_images=(None, None),  # Deaktiviere Avatare
                        show_copy_button=True,
                        show_share_button=True
                    )
                    
                    # Eingabebereich
                    with gr.Row():
                        user_input = gr.Textbox(
                            placeholder="Teilen Sie Ihre Gedanken mit Dr. Franz...", 
                            label="Ihre Aussage",
                            scale=4,
                            elem_id="user-input",
                            show_label=True
                        )
                        send = gr.Button("Senden", variant="primary", elem_id="send-btn")
                    
                    # Aktionsbereich
                    with gr.Row():
                        clear = gr.Button("Neue Sitzung", elem_id="clear-btn")
                        thinking = gr.HTML(
                            "<div id='thinking-indicator' style='display:none; text-align:center;'>"
                            "<i>Dr. Franz denkt nach...</i></div>"
                        )
                
                # Informationsbereich (rechte Spalte)
                with gr.Column(scale=1):
                    gr.Markdown(f"### Über {config.CHATBOT_NAME}")
                    gr.Markdown("""
                    Dr. Franz ist ein experimenteller KI-Psychoanalytiker, der Ihre Gedanken und Emotionen analysiert.
                    
                    **Hinweis:** Dieser Chatbot dient nur der Unterhaltung und ersetzt keine professionelle psychologische Beratung.
                    
                    **Funktionen:**
                    - Psychoanalytische Gesprächsführung
                    - Emotionsanalyse
                    - Kontextbewusstsein
                    
                    Dieser Chatbot verwendet die HuggingFace Inference API.
                    """)
                    
                    # Optionaler Bereich für Stimmungsanzeige
                    mood_indicator = gr.HTML(
                        "<div id='mood-container' style='text-align:center; margin-top:20px;'>"
                        "<div id='mood-label'>Therapeutische Intensität</div>"
                        "<div id='mood-indicator' style='font-size:24px;'>😐</div>"
                        "</div>"
                    )
            
            # JavaScript für dynamische UI-Elemente
            gr.HTML("""
            <script>
                // Funktion zum Anzeigen des "Denkt nach..."-Indikators
                function showThinking() {
                    document.getElementById('thinking-indicator').style.display = 'block';
                    
                    // Zufällige Stimmung anzeigen
                    const moods = ['🧐', '🤔', '😑', '😒', '🙄'];
                    document.getElementById('mood-indicator').innerText = moods[Math.floor(Math.random() * moods.length)];
                }
                
                // Funktion zum Ausblenden des "Denkt nach..."-Indikators
                function hideThinking() {
                    document.getElementById('thinking-indicator').style.display = 'none';
                    
                    // Zufällige Stimmung anzeigen
                    const moods = ['😏', '🧐', '😐', '🤨', '😌'];
                    document.getElementById('mood-indicator').innerText = moods[Math.floor(Math.random() * moods.length)];
                }
                
                // Event-Listener für den Senden-Button
                document.addEventListener('DOMContentLoaded', function() {
                    const sendBtn = document.getElementById('send-btn');
                    if (sendBtn) {
                        sendBtn.addEventListener('click', showThinking);
                    }
                    
                    // Beobachter für Änderungen im Chat-Bereich
                    const observer = new MutationObserver(function(mutations) {
                        hideThinking();
                    });
                    
                    // Beobachtung starten, sobald das Element verfügbar ist
                    setTimeout(function() {
                        const chatbox = document.getElementById('chatbox');
                        if (chatbox) {
                            observer.observe(chatbox, { childList: true, subtree: true });
                        }
                    }, 1000);
                });
            </script>
            """)
            
            # Event-Handler
            def respond(msg, history):
                if not msg.strip():
                    return history, ""
                
                # Kurze Verzögerung für natürlicheres Gefühl
                time.sleep(0.5)
                
                # Chat-Funktion aufrufen
                reply = self.chat_function(msg)
                
                history = history or []
                history.append((msg, reply))
                return history, ""
            
            send.click(respond, inputs=[user_input, chatbot], outputs=[chatbot, user_input])
            user_input.submit(respond, inputs=[user_input, chatbot], outputs=[chatbot, user_input])
            clear.click(self.clear_function, inputs=[], outputs=[chatbot, user_input])
        
        return demo
    
    def launch_interface(self, demo: gr.Blocks) -> None:
        """
        Startet das Gradio-Interface
        
        Args:
            demo: Das zu startende Gradio-Interface
        """
        demo.launch(
            server_name=config.SERVER_NAME,
            share=config.SHARE,
            show_error=config.SHOW_ERROR
        )