File size: 8,930 Bytes
7ff48bf
 
 
2ed4dc0
b840af0
 
 
7ff48bf
6701f02
 
b8f9cf8
b840af0
7ff48bf
12f1160
7ff48bf
 
b840af0
e837ccf
b840af0
 
 
e837ccf
 
7ff48bf
 
 
90db298
12f1160
 
 
 
b840af0
 
12f1160
b840af0
 
90db298
 
 
 
e8135ea
b840af0
12f1160
b840af0
90db298
b840af0
 
 
12f1160
 
 
 
 
 
 
 
90db298
 
12f1160
b840af0
d1b86e8
fbb549a
b840af0
12f1160
90db298
 
 
 
fbb549a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da3347d
12f1160
d1b86e8
0c47194
6968345
b840af0
1e86e8f
90db298
2ddb996
90db298
 
1e86e8f
90db298
b840af0
 
 
 
 
 
d1b86e8
b840af0
 
 
 
 
 
 
 
 
 
 
 
01e34c4
b840af0
 
 
 
 
 
 
01e34c4
b840af0
 
 
 
 
 
 
01e34c4
b840af0
 
 
d1b86e8
b840af0
1e86e8f
b840af0
 
7ff48bf
d1b86e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ff48bf
79eb47d
b840af0
 
 
 
 
 
 
 
7ff48bf
 
b840af0
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
262
263
264
265
266
267
268
269
270
271
272
273
274
from huggingface_hub import InferenceClient
from typing import List, Tuple
import gradio as gr

# Ensure you have the required libraries installed

# Chatbot configuration
class ChatConfig:
    MODEL = "google/gemma-3-27b-it"
    # MODEL = "mistralai/Mistral-7B-Instruct-v0.1"
    # MODEL = "google/gemma-2-9b-it"
    DEFAULT_SYSTEM_MSG = "You are a extremely smart and useful Chatbot."
    DEFAULT_MAX_TOKENS = 1024
    DEFAULT_TEMP = 0.4
    DEFAULT_TOP_P = 0.95

import os
HF_TOKEN = os.getenv("HUGGING_FACE_HUB_TOKEN")

# Not recommended to hardcode your token in the script for security reasons.
# HF_TOKEN = "hf_YOUR_TOKEN_HERE"

client = InferenceClient(ChatConfig.MODEL, token=HF_TOKEN)

def generate_response(

    message: str,

    history: List[Tuple[str, str]],

    system_message: str = ChatConfig.DEFAULT_SYSTEM_MSG,

    max_tokens: int = ChatConfig.DEFAULT_MAX_TOKENS,

    temperature: float = ChatConfig.DEFAULT_TEMP,

    top_p: float = ChatConfig.DEFAULT_TOP_P

) -> str:
    
    messages = [{"role": "system", "content": system_message}]
    
    # Conversation history
    for user_msg, bot_msg in history:
        if user_msg:
            messages.append({"role": "user", "content": user_msg})
        if bot_msg:
            messages.append({"role": "assistant", "content": bot_msg})
    
    messages.append({"role": "user", "content": message})
    
    response = ""

    # Stream the response
    # The stream=True parameter allows for real-time response generation
    for chunk in client.chat_completion(
        messages,
        max_tokens=max_tokens,
        stream=True,
        temperature=temperature,
        top_p=top_p,
    ):
        token = chunk.choices[0].delta.content or ""
        response += token
        yield response


def create_interface() -> gr.ChatInterface:
    """Create and configure the chat interface."""
    # Custom CSS for a modern look
    custom_css = """

    body {

        background: linear-gradient(to right, #a8c0ff, #fafdff);

        font-family: 'Comic Sans MS', sans-serif;

    }



    .chatbot .message { 

        border-radius: 12px; 

        margin: 5px; 

        padding: 10px; 

    }

    .chatbot .user-message { 

        background-color: #b3e5fc;

        color: #0d47a1; 

    }

    .chatbot .bot-message { 

        background-color: #e3f2fd;

        color: #0d47a1;

    }

    .gr-button { 

        border-radius: 8px; 

        padding: 8px 16px; 

    }

    """

    with gr.Blocks(css=custom_css) as app:
        gr.Markdown("# Your Gemma Three-(end) 💎")

        # Custom chatbot 
        chatbot = gr.Chatbot(
            label="Gemma Chat",
            avatar_images=("./user.png", "./gemma.png"),
            height=450,
            show_copy_button=True
        )

        # Chat interface
        interface = gr.ChatInterface(
            fn=generate_response,
            chatbot=chatbot,
            title="Your Gemma 3-(iend)",
            theme=gr.themes.Soft(),
            css=custom_css,
            additional_inputs=[
                gr.Textbox(
                    value=ChatConfig.DEFAULT_SYSTEM_MSG,
                    label="System Prompt (You can change the text below)",
                    lines=2,
                    placeholder="Enter system message..."
                ),
                gr.Slider(
                    minimum=1,
                    maximum=8192,
                    value=ChatConfig.DEFAULT_MAX_TOKENS,
                    step=1,
                    label="Max Tokens (Response Length)",
                    info="Controls response length"
                ),
                gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=ChatConfig.DEFAULT_TEMP,
                    step=0.1,
                    label="Temperature (0.1-1.0)",
                    info="Controls randomness"
                ),
                gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=ChatConfig.DEFAULT_TOP_P,
                    step=0.05,
                    label="Top-P (0.1-1.0)",
                    info="Controls diversity"
                )
            ],

            additional_inputs_accordion=gr.Accordion(label="Advanced Settings", open=False)
        )
    
    return app


# def create_interface() -> gr.Blocks:
#     """Create and configure the chat interface."""
#     # Custom CSS for a modern look
#     custom_css = """
#     body {
#         background: linear-gradient(to right, #a8c0ff, #fafdff);
#         font-family: 'Comic Sans MS', sans-serif;
#     }

#     .chatbot .message { 
#         border-radius: 12px; 
#         margin: 5px; 
#         padding: 10px; 
#     }
#     .chatbot .user-message { 
#         background-color: #b3e5fc;
#         color: #0d47a1; 
#     }
#     .chatbot .bot-message { 
#         background-color: #e3f2fd;
#         color: #0d47a1;
#     }
#     .gr-button { 
#         border-radius: 8px; 
#         padding: 8px 16px; 
#     }
#     """
    
#     # JavaScript pour jouer un son à la soumission
#     custom_js = """
#     function setupSubmitSound() {
#         // Create the audio element for the sound
#         const submitSound = new Audio('/gradio_api/file=submit_sound.mp3');
        
#         // Fonction pour attacher l'écouteur d'événement
#         function attachSoundToButton() {
#             // Rechercher le bouton de soumission dans l'interface
#             const submitButton = document.querySelector('button.send-btn') || 
#                                  document.querySelector('button[aria-label="Submit"]') ||
#                                  document.querySelector('.submit');
            
#             if (submitButton) {
#                 console.log('Found submit button, attaching sound');
#                 submitButton.addEventListener('click', function() {
#                     submitSound.currentTime = 0; // Réinitialiser le son
#                     submitSound.play();
#                 });
#             } else {
#                 // Si le bouton n'est pas encore disponible, réessayer plus tard
#                 console.log('Button not found, trying again in 500ms');
#                 setTimeout(attachSoundToButton, 500);
#             }
#         }
        
#         // Démarrer la recherche du bouton
#         attachSoundToButton();
#     }
    
#     // Appeler la fonction d'initialisation
#     setupSubmitSound();
#     """

#     with gr.Blocks(css=custom_css, js=custom_js) as app:
#         gr.Markdown("# Your Gemma Three-(end) 💎")

#         # Custom chatbot 
#         chatbot = gr.Chatbot(
#             label="Gemma Chat",
#             avatar_images=("./user.png", "./gemma.png"),
#             height=450,
#             show_copy_button=True
#         )

#         # Chat interface
#         interface = gr.ChatInterface(
#             fn=generate_response,
#             chatbot=chatbot,
#             title="Your Gemma 3-(iend)",
#             theme=gr.themes.Soft(),
#             additional_inputs=[
#                 gr.Textbox(
#                     value=ChatConfig.DEFAULT_SYSTEM_MSG,
#                     label="System Prompt (You can change the text below)",
#                     lines=2,
#                     placeholder="Enter system message..."
#                 ),
#                 gr.Slider(
#                     minimum=1,
#                     maximum=8192,
#                     value=ChatConfig.DEFAULT_MAX_TOKENS,
#                     step=1,
#                     label="Max Tokens (Response Length)",
#                     info="Controls response length"
#                 ),
#                 gr.Slider(
#                     minimum=0.1,
#                     maximum=1.0,
#                     value=ChatConfig.DEFAULT_TEMP,
#                     step=0.1,
#                     label="Temperature (0.1-1.0)",
#                     info="Controls randomness"
#                 ),
#                 gr.Slider(
#                     minimum=0.1,
#                     maximum=1.0,
#                     value=ChatConfig.DEFAULT_TOP_P,
#                     step=0.05,
#                     label="Top-P (0.1-1.0)",
#                     info="Controls diversity"
#                 )
#             ],
#             additional_inputs_accordion=gr.Accordion(label="Advanced Settings", open=False)
#         )
    
#     return app

def main():
    app = create_interface()
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_api=False,
        show_error=True,
        debug=True
    )

if __name__ == "__main__":
    main()