Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
301 lines (244 loc) · 11.8 KB
/
Copy pathscript.js
File metadata and controls
301 lines (244 loc) · 11.8 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
document.addEventListener("DOMContentLoaded", () => {
const welcomeMain = document.getElementById("welcome-main");
const welcomeSub = document.getElementById("welcome-sub");
const user1Lang = document.getElementById("user1-lang");
const user2Lang = document.getElementById("user2-lang");
const user1Input = document.getElementById("user1-input");
const user2Input = document.getElementById("user2-input");
const user1SendBtn = document.getElementById("user1-send-btn");
const user2SendBtn = document.getElementById("user2-send-btn");
const chatDisplay = document.getElementById("chat-display");
const micBtn = document.getElementById("mic-btn");
const tapPill = document.getElementById("tap-pill");
const clearChatBtn = document.getElementById("clear-chat-btn");
let isRecording = false;
const conversationContexts = {
general: {
user1Label: "User 1",
user2Label: "User 2",
user1Placeholder: { en: "Write here...", sw: "Andika hapa...", ha: "Andika hano..." },
user2Placeholder: { en: "Write here...", sw: "Andika hapa...", ha: "Andika hano..." }
},
medical: {
user1Label: "Doctor 👨⚕️",
user2Label: "Patient 🤒",
user1Placeholder: { en: "Ask symptoms or diagnosis...", sw: "Uliza dalili au vipimo...", ha: "Baza ibimenyetso..." },
user2Placeholder: { en: "Describe how you feel...", sw: "Eleza unavyojisikia...", ha: "Sigura uko wumva..." }
},
education: {
user1Label: "Teacher 👨🏫",
user2Label: "Student 🧑🎓",
user1Placeholder: { en: "Ask question or give task...", sw: "Uliza swali au toa kazi...", ha: "Baza ikibazo..." },
user2Placeholder: { en: "Write your answer...", sw: "Andika jibu lako...", ha: "Andika inyishu..." }
},
trade: {
user1Label: "Buyer 🛒",
user2Label: "Seller 🏷️",
user1Placeholder: { en: "Ask price or quality...", sw: "Uliza bei au ubora...", ha: "Baza igiciro..." },
user2Placeholder: { en: "State price or offer...", sw: "Taja bei au ofa...", ha: "Vuga igiciro..." }
}
};
let activeContext = "general";
function injectContextSelector() {
const speakerBar = document.querySelector(".speaker-selector-bar");
if (!speakerBar) return;
const contextContainer = document.createElement("div");
contextContainer.className = "context-selector-wrapper";
contextContainer.style.cssText = "display:flex; align-items:center; justify-content:space-between; padding:6px 12px; background:#e9ecef; border-bottom:1px solid #ccc; font-size:11px; font-weight:bold;";
contextContainer.innerHTML = `
<label for="chat-context-select"><i class="fa-solid fa-users-rectangle"></i> Conversation Role:</label>
<select id="chat-context-select" style="font-size:11px; padding:2px 4px; border-radius:4px; border:1px solid #aaa;">
<option value="general">General (User 1 & User 2)</option>
<option value="medical">Doctor & Patient</option>
<option value="education">Teacher & Student</option>
<option value="trade">Buyer & Seller</option>
</select>
`;
speakerBar.parentNode.insertBefore(contextContainer, speakerBar);
document.getElementById("chat-context-select").addEventListener("change", (e) => {
activeContext = e.target.value;
applyContextUI();
});
}
function applyContextUI() {
const ctx = conversationContexts[activeContext];
const u1Label = document.querySelector('label[for="user1-lang"]');
const u2Label = document.querySelector('label[for="user2-lang"]');
if (u1Label) u1Label.textContent = ctx.user1Label;
if (u2Label) u2Label.textContent = ctx.user2Label;
user1Input.placeholder = ctx.user1Placeholder[user1Lang.value] || ctx.user1Placeholder.en;
user2Input.placeholder = ctx.user2Placeholder[user2Lang.value] || ctx.user2Placeholder.en;
}
const dictionary = {
"hello": { "sw": "habari", "ha": "mwakeye" },
"hi": { "sw": "mambo", "ha": "mwakeye" },
"how are you": { "sw": "habari gani", "ha": "amakuru" },
"good morning": { "sw": "habari ya asubuhi", "ha": "mwaramutse" },
"good night": { "sw": "usiku mwema", "ha": "irome vyiza" },
"thank you": { "sw": "asante", "ha": "urakoze" },
"welcome": { "sw": "karibu", "ha": "mwakaribushwa" },
"yes": { "sw": "ndiyo", "ha": "ego" },
"no": { "sw": "hapana", "ha": "oya" },
"where does it hurt": { "sw": "wapi wanahisi maumivu", "ha": "ubabara he" },
"i have a headache": { "sw": "ninaumwa na kichwa", "ha": "ndarwaye umutwe" },
"fever": { "sw": "homa", "ha": "inyota" },
"medicine": { "sw": "dawa", "ha": "umuti" },
"take this medicine": { "sw": "kunywa dawa hii", "ha": "fata uyu muti" },
"do you understand": { "sw": "unaelewa", "ha": "urabyumva" },
"i understand": { "sw": "naelewa", "ha": "narabyumvise" },
"how much": { "sw": "ni kiasi gani", "ha": "ni angahe" },
"too expensive": { "sw": "ghali sana", "ha": "zira cane" },
"habari": { "en": "hello", "ha": "mwakeye" },
"mambo": { "en": "hi", "ha": "mwakeye" },
"habari gani": { "en": "how are you", "ha": "amakuru" },
"asante": { "en": "thank you", "ha": "urakoze" },
"karibu": { "en": "welcome", "ha": "mwakaribushwa" },
"ninaumwa na kichwa": { "en": "i have a headache", "ha": "ndarwaye umutwe" },
"mwakeye": { "en": "hello", "sw": "habari" },
"amakuru": { "en": "how are you", "sw": "habari gani" },
"urakoze": { "en": "thank you", "sw": "asante" },
"mwakaribushwa": { "en": "welcome", "sw": "karibu" }
};
const headerTranslations = {
"en": { main: "WELCOME! SPEAK OR WRITE YOUR LANGUAGE", sub: "(Karibu! sema au andika lugha yako)" },
"sw": { main: "KARIBU! SEMA AU ANDIKA LUGHA YAKO", sub: "(Welcome! speak or write your language)" },
"ha": { main: "MWAKARIBUSHWA! OYAGA MUBANJE KUANDIKA", sub: "(Welcome! speak or write your language)" }
};
function getActiveSpeaker() {
const checkedRadio = document.querySelector('input[name="active-speaker"]:checked');
return checkedRadio ? parseInt(checkedRadio.value) : 1;
}
function updateHeaderLanguage(langCode) {
if (headerTranslations[langCode]) {
welcomeMain.textContent = headerTranslations[langCode].main;
welcomeSub.textContent = headerTranslations[langCode].sub;
}
}
user1Lang.addEventListener("change", (e) => {
if (getActiveSpeaker() === 1) updateHeaderLanguage(e.target.value);
applyContextUI();
});
user2Lang.addEventListener("change", (e) => {
if (getActiveSpeaker() === 2) updateHeaderLanguage(e.target.value);
applyContextUI();
});
function translateText(text, targetLang, sourceLang) {
if (!text) return "";
if (sourceLang === targetLang) return text;
const cleanText = text.toLowerCase().trim().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g, "");
if (dictionary[cleanText] && dictionary[cleanText][targetLang]) {
return dictionary[cleanText][targetLang];
}
const words = cleanText.split(" ");
const translatedWords = words.map(word => {
if (dictionary[word] && dictionary[word][targetLang]) {
return dictionary[word][targetLang];
}
return word;
});
return translatedWords.join(" ");
}
user1SendBtn.addEventListener("click", () => sendSmsMessage(1));
user2SendBtn.addEventListener("click", () => sendSmsMessage(2));
function sendSmsMessage(sender) {
const inputElem = sender === 1 ? user1Input : user2Input;
const text = inputElem.value.trim();
if (!text) return;
const sourceLang = sender === 1 ? user1Lang.value : user2Lang.value;
const targetLang = sender === 1 ? user2Lang.value : user1Lang.value;
updateHeaderLanguage(sourceLang);
const translatedText = translateText(text, targetLang, sourceLang);
renderSentAndReceivedBubbles(sender, text, translatedText, targetLang);
inputElem.value = "";
}
function renderSentAndReceivedBubbles(sender, originalText, translatedText, targetLang) {
const now = new Date();
const timeStr = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const senderRole = sender === 1 ? conversationContexts[activeContext].user1Label : conversationContexts[activeContext].user2Label;
const receiverRole = sender === 1 ? conversationContexts[activeContext].user2Label : conversationContexts[activeContext].user1Label;
const sentBubble = document.createElement("div");
sentBubble.classList.add("sms-bubble", `sent-by-user${sender}`);
sentBubble.style.opacity = "0.9";
sentBubble.innerHTML = `
<div class="sms-meta">
<span>Kumbukumbu (${senderRole})</span>
<span>${timeStr}</span>
</div>
<div class="sms-original">Umetuma: "${originalText}"</div>
<div class="sms-sub-translated" style="font-size:11px; color:#555;">Imetafsiriwa: "${translatedText}"</div>
`;
chatDisplay.appendChild(sentBubble);
const receiverNumber = sender === 1 ? 2 : 1;
const receivedBubble = document.createElement("div");
receivedBubble.classList.add("sms-bubble", `sent-by-user${receiverNumber}`);
receivedBubble.innerHTML = `
<div class="sms-meta">
<span>Ujumbe Mpya kwa ${receiverRole}</span>
<span>${timeStr}</span>
</div>
<div class="sms-translated">${translatedText}</div>
<div class="sms-original" style="border-top:1px dashed #ccc; margin-top:4px; padding-top:4px;">Kutoka kwa ${senderRole}: "${originalText}"</div>
<div class="sms-actions">
<button class="sms-action-btn listen-sms-btn"><i class="fa-solid fa-volume-high"></i> Listen</button>
<button class="sms-action-btn copy-sms-btn"><i class="fa-solid fa-copy"></i> Copy</button>
</div>
`;
receivedBubble.querySelector(".listen-sms-btn").addEventListener("click", () => {
speakAudio(translatedText, targetLang);
});
receivedBubble.querySelector(".copy-sms-btn").addEventListener("click", (e) => {
navigator.clipboard.writeText(translatedText);
const btn = e.currentTarget;
btn.innerHTML = `<i class="fa-solid fa-check"></i> Copied!`;
setTimeout(() => { btn.innerHTML = `<i class="fa-solid fa-copy"></i> Copy`; }, 1500);
});
chatDisplay.appendChild(receivedBubble);
chatDisplay.scrollTop = chatDisplay.scrollHeight;
}
function speakAudio(text, langCode) {
if ("speechSynthesis" in window) {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = langCode === "sw" ? "sw-TZ" : "en-US";
window.speechSynthesis.speak(utterance);
}
}
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (SpeechRecognition) {
const recognition = new SpeechRecognition();
const handleSpeech = () => {
const activeSpeaker = getActiveSpeaker();
const sourceLang = activeSpeaker === 1 ? user1Lang.value : user2Lang.value;
if (!isRecording) {
updateHeaderLanguage(sourceLang);
recognition.lang = sourceLang === "sw" ? "sw-TZ" : "en-US";
recognition.start();
micBtn.classList.add("recording");
isRecording = true;
} else {
recognition.stop();
micBtn.classList.remove("recording");
isRecording = false;
}
};
micBtn.addEventListener("click", handleSpeech);
tapPill.addEventListener("click", handleSpeech);
recognition.onresult = (e) => {
const transcript = e.results[0][0].transcript;
micBtn.classList.remove("recording");
isRecording = false;
const activeSpeaker = getActiveSpeaker();
const inputElem = activeSpeaker === 1 ? user1Input : user2Input;
inputElem.value = transcript;
};
recognition.onerror = () => {
micBtn.classList.remove("recording");
isRecording = false;
};
}
clearChatBtn.addEventListener("click", () => {
chatDisplay.innerHTML = "";
});
injectContextSelector();
applyContextUI();
});