Denis202 commited on
Commit
69adcc4
Β·
verified Β·
1 Parent(s): 4ab418d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +193 -90
app.py CHANGED
@@ -1,98 +1,201 @@
 
1
  import gradio as gr
2
- import time
3
-
4
- def chat_response(message, history):
5
- # Simulate a response with a delay
6
- time.sleep(1)
7
- if not message or message.strip() == "":
8
- return history, "Tafadhali andika ujumbe..."
9
- response = f"Majibu: {message}"
10
- new_history = history + [
11
- {"role": "user", "content": message},
12
- {"role": "assistant", "content": response},
13
- ]
14
- return new_history, ""
15
-
16
-
17
- # ---- APP UI ----
 
 
 
 
 
 
 
 
 
 
 
 
18
  with gr.Blocks(
19
- theme=gr.themes.Base(),
 
20
  css="""
21
- .gradio-container {max-width: 650px; margin:30px auto; border-radius:16px;}
22
- .header {text-align:center; margin:16px 0; font-size:1.2em;}
23
- #chat_area {background:#fff; border-radius:12px; min-height:340px; overflow-y:auto; box-shadow:0 3px 16px #eee;}
24
- .input-row {display:flex; gap:8px; margin-top:8px;}
25
- textarea {flex:1; resize:none; border-radius:10px; padding:10px; font-size:1em;}
26
- .button-primary {background:#1db954; color:#fff; border-radius:10px; font-weight:bold;}
27
- .button-secondary {background:#ff6666; color:#fff; border-radius:10px; font-weight:bold;}
28
- body.dark {background-color:#1e1e1e; color:#fff;}
29
- #chat_area.dark {background:#333;}
30
- @media(max-width: 680px){.gradio-container{max-width: 98vw; padding: 0 2vw;}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  """
32
  ) as demo:
33
-
34
- # Header
35
- gr.HTML('<div class="header"><b>KiswahiliChetu</b><br>Jifunze Kiswahili fasaha na LLM</div>')
36
-
37
- # State
38
- dark_mode = gr.State(False)
39
- state = gr.State([])
40
-
41
- # Toggle function (backend)
42
- def toggle_theme(current):
43
- return not current
44
-
45
- # Create toggle button
46
- toggle_btn = gr.Button("πŸŒ™ Toggle Dark Mode", variant="secondary")
47
-
48
- # Try JS injection safely
49
- try:
50
- toggle_btn.click(
51
- toggle_theme,
52
- inputs=dark_mode,
53
- outputs=dark_mode,
54
- _js="() => { document.body.classList.toggle('dark'); }"
55
- )
56
- except TypeError:
57
- # Older Gradio fallback (no _js support)
58
- toggle_btn.click(toggle_theme, inputs=dark_mode, outputs=dark_mode)
59
-
60
- # Chat area
61
- chat = gr.Chatbot(elem_id="chat_area", label="", show_copy_button=True, value=[], type="messages")
62
-
63
- # Input row
64
  with gr.Row():
65
- msg_input = gr.Textbox(placeholder="Andika ujumbe wa Kiswahili...", lines=3, label="")
66
- send_btn = gr.Button("Tuma", elem_classes="button-primary")
67
- clear_btn = gr.Button("Futa", elem_classes="button-secondary")
68
-
69
- # Examples section
70
- with gr.Accordion("πŸ“š Mifano ya Maswali", open=False):
71
- gr.Examples(
72
- examples=[["Habari yako?"], ["Jina lako nani?"], ["Eleza kuhusu Tanzania"]],
73
- inputs=msg_input,
74
- )
75
-
76
- # Main message handler
77
- def process(msg, chat_history, state):
78
- if not msg.strip():
79
- return chat_history, "Tafadhali andika ujumbe..."
80
- chat_history.append({"role": "user", "content": msg})
81
- time.sleep(0.8)
82
- response = f"Majibu: {msg}"
83
- chat_history.append({"role": "assistant", "content": response})
84
- return chat_history, ""
85
-
86
- # Clear chat function
87
- def clear_chat():
88
- return [], ""
89
-
90
- # Button and Enter bindings
91
- send_btn.click(process, [msg_input, chat, state], [chat, msg_input])
92
- msg_input.submit(process, [msg_input, chat, state], [chat, msg_input])
93
- clear_btn.click(clear_chat, None, [chat, msg_input])
94
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
- # ---- LAUNCH ----
97
  if __name__ == "__main__":
98
- demo.launch(server_name="0.0.0.0", share=False, show_error=True)
 
 
 
 
 
1
+ import torch
2
  import gradio as gr
3
+ from chat import KiswahiliChatbot
4
+ import os
5
+ import logging
6
+
7
+ # Set up logging
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # Initialize chatbot
12
+ try:
13
+ chatbot = KiswahiliChatbot()
14
+ logger.info("βœ… Chatbot imeanzishwa kikamilifu!")
15
+ except Exception as e:
16
+ logger.error(f"❌ Imeshindwa kuanzisha chatbot: {e}")
17
+ chatbot = None
18
+
19
+ def chat_interface(message, history):
20
+ """Handle chat interface interactions"""
21
+ if chatbot is None:
22
+ return "Samahani, kuna hitilafu ya mfumo. Tafadhali jaribu tena baadaye."
23
+
24
+ if not message.strip():
25
+ return "Tafadhali andika ujumbe..."
26
+
27
+ response = chatbot.chat(message)
28
+ return response
29
+
30
+ # Create Gradio interface with Tanzania flag colors
31
  with gr.Blocks(
32
+ title="KiswahiliChetu",
33
+ theme=gr.themes.Soft(primary_hue="blue"),
34
  css="""
35
+ .gradio-container {
36
+ max-width: 1200px;
37
+ margin: auto;
38
+ font-family: 'Arial', sans-serif;
39
+ background: #f0f2f5;
40
+ }
41
+
42
+ .tanzania-title-shell {
43
+ display: inline-block;
44
+ padding: 12px 25px;
45
+ background: white;
46
+ border-radius: 25px;
47
+ box-shadow: 0px 4px 10px rgba(0,0,0,0.15);
48
+ margin-bottom: 15px !important;
49
+ }
50
+
51
+ .tanzania-title {
52
+ font-size: 3em !important;
53
+ font-weight: bold !important;
54
+ text-align: center;
55
+ background: linear-gradient(to bottom,
56
+ #1DB954 0% 35%, /* Green */
57
+ #FFD700 35% 40%, /* Thin Yellow */
58
+ #000000 40% 60%, /* Black */
59
+ #FFD700 60% 65%, /* Thin Yellow */
60
+ #87CEEB 65% 100% /* Sky Blue */
61
+ );
62
+ -webkit-background-clip: text;
63
+ -webkit-text-fill-color: transparent;
64
+ background-clip: text;
65
+ display: inline-block;
66
+ }
67
+
68
+ .tanzania-subtitle {
69
+ text-align: center;
70
+ color: #666;
71
+ margin-bottom: 30px !important;
72
+ font-size: 1.2em;
73
+ }
74
+
75
+ .chat-container {
76
+ background: #f8f9fa;
77
+ padding: 20px;
78
+ border-radius: 15px;
79
+ border: 2px solid #e9ecef;
80
+ }
81
+
82
+ .input-container {
83
+ background: #ffffff;
84
+ padding: 20px;
85
+ border-radius: 15px;
86
+ border: 2px solid #e9ecef;
87
+ }
88
+
89
+ .gradio-button {
90
+ border-radius: 8px;
91
+ font-weight: bold;
92
+ }
93
+
94
+ .examples-section {
95
+ background: #fffae6;
96
+ padding: 15px;
97
+ border-radius: 10px;
98
+ border-left: 4px solid #FCD116;
99
+ }
100
  """
101
  ) as demo:
102
+
103
+ # Header with Tanzania flag colors
104
+ gr.HTML("""
105
+ <div style="text-align: center;">
106
+ <div class="tanzania-title-shell">
107
+ <span class="tanzania-title">KiswahiliChetu</span>
108
+ </div>
109
+ <p class="tanzania-subtitle">Jifunze kiswahili fasaha, uliza maswali na KiswahiliChetu akili Unde</p>
110
+ </div>
111
+ """)
112
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  with gr.Row():
114
+ # LEFT SIDE: Input section
115
+ with gr.Column(scale=1, min_width=400):
116
+ with gr.Column(elem_classes="input-container"):
117
+ gr.Markdown("### ✍️ Ujumbe Wako")
118
+
119
+ msg = gr.Textbox(
120
+ label="",
121
+ placeholder="Andika hapa kwa Kiswahili...",
122
+ lines=4,
123
+ max_lines=6,
124
+ show_label=False
125
+ )
126
+
127
+ with gr.Row():
128
+ submit_btn = gr.Button("πŸ“€ Tuma", variant="primary", size="lg")
129
+ clear_btn = gr.Button("πŸ—‘οΈ Futa Mazungumzo", variant="secondary")
130
+
131
+ # Examples section
132
+ with gr.Accordion("πŸ“š Mifano ya Maswali", open=True):
133
+ gr.Examples(
134
+ examples=[
135
+ ["Habari yako?"],
136
+ ["Jina lako nani?"],
137
+ ["Unaweza kusema Kiswahili?"],
138
+ ["Eleza kuhusu Tanzania"],
139
+ ["Nini maana ya 'Hakuna matata'?"]
140
+ ],
141
+ inputs=msg,
142
+ label="Bonyeza mfano wa swali:"
143
+ )
144
+
145
+ # RIGHT SIDE: Chat section
146
+ with gr.Column(scale=2, min_width=600):
147
+ with gr.Column(elem_classes="chat-container"):
148
+ gr.Markdown("### πŸ’¬ Mazungumzo")
149
+ chatbot_ui = gr.Chatbot(
150
+ height=500,
151
+ show_copy_button=True,
152
+ show_share_button=True,
153
+ avatar_images=(
154
+ None,
155
+ "https://api.dicebear.com/7.x/bottts/svg?seed=swahili&backgroundColor=1eb53a"
156
+ )
157
+ )
158
+
159
+ # System info and footer
160
+ with gr.Accordion("πŸ“Š Taarifa ya Mfumo", open=False):
161
+ gr.Markdown(f"""
162
+ **Gradio Version:** {gr.__version__}
163
+ **Device:** {'GPU' if torch.cuda.is_available() else 'CPU'}
164
+ """)
165
+
166
+ gr.Markdown("---")
167
+ gr.Markdown("""
168
+ <div style='text-align: center; color: #666;'>
169
+ <strong>πŸ‡ΉπŸ‡Ώ Imetengenezwa kwa upendo wa lugha ya Kiswahili na Tanzania</strong>
170
+ </div>
171
+ """)
172
+
173
+ # Event handlers
174
+ def process_message(message, history):
175
+ response = chat_interface(message, history)
176
+ return history + [(message, response)], ""
177
+
178
+ msg.submit(
179
+ process_message,
180
+ inputs=[msg, chatbot_ui],
181
+ outputs=[chatbot_ui, msg]
182
+ )
183
+
184
+ submit_btn.click(
185
+ process_message,
186
+ inputs=[msg, chatbot_ui],
187
+ outputs=[chatbot_ui, msg]
188
+ )
189
+
190
+ clear_btn.click(
191
+ lambda: None,
192
+ inputs=None,
193
+ outputs=chatbot_ui
194
+ )
195
 
 
196
  if __name__ == "__main__":
197
+ demo.launch(
198
+ server_name="0.0.0.0",
199
+ share=False,
200
+ show_error=True
201
+ )