Spaces:
Runtime error
Runtime error
File size: 10,792 Bytes
4032dfd f0ed4e5 4032dfd 55a08d2 abd4ad0 55a08d2 abd4ad0 55a08d2 abd4ad0 55a08d2 abd4ad0 55a08d2 | 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | const wordInput = document.getElementById('wordInput');
const loading = document.getElementById('loading');
const errorDiv = document.getElementById('error');
const resultDiv = document.getElementById('result');
const errorResult = document.getElementById('errorResult');
let selectedLanguage = 'english';
const placeholders = {
english: 'Type an English word...',
telugu: 'తెలుగు పదం టైప్ చేయండి...',
hindi: 'हिंदी शब्द टाइप करें...',
sanskrit: 'संस्कृत शब्दं लिखतु...',
};
// Load saved API key
const savedKey = localStorage.getItem('groq_api_key') || '';
document.getElementById('apiKeyInput').value = savedKey;
wordInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') lookupWord();
});
/* ========== Voice Search (Web Speech API) ========== */
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = null;
let isListening = false;
const voiceLangMap = {
english: 'en-US',
telugu: 'te-IN',
hindi: 'hi-IN',
sanskrit: 'sa-IN',
};
function toggleVoice() {
if (!SpeechRecognition) {
alert('Voice search is not supported in this browser. Please use Chrome or Edge.');
return;
}
if (isListening) {
recognition.stop();
return;
}
recognition = new SpeechRecognition();
recognition.lang = voiceLangMap[selectedLanguage] || 'en-US';
recognition.interimResults = true;
recognition.maxAlternatives = 1;
recognition.continuous = false;
const micBtn = document.getElementById('micBtn');
recognition.onstart = () => {
isListening = true;
micBtn.classList.add('listening');
wordInput.placeholder = 'Listening...';
};
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
wordInput.value = transcript;
if (event.results[0].isFinal) {
lookupWord();
}
};
recognition.onerror = (event) => {
console.error('Speech error:', event.error);
if (event.error === 'not-allowed') {
alert('Microphone access denied. Please allow microphone permission.');
}
};
recognition.onend = () => {
isListening = false;
micBtn.classList.remove('listening');
wordInput.placeholder = placeholders[selectedLanguage] || 'Type a word...';
};
recognition.start();
}
// Hide mic button if Speech API not supported
if (!SpeechRecognition) {
const micBtn = document.getElementById('micBtn');
if (micBtn) micBtn.style.display = 'none';
}
function selectLanguage(btn) {
document.querySelectorAll('.lang-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
selectedLanguage = btn.dataset.lang;
wordInput.placeholder = placeholders[selectedLanguage] || 'Type a word...';
wordInput.focus();
}
function toggleSettings() {
const panel = document.getElementById('settingsPanel');
panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}
function saveApiKey() {
const key = document.getElementById('apiKeyInput').value.trim();
localStorage.setItem('groq_api_key', key);
toggleSettings();
}
async function lookupWord() {
const word = wordInput.value.trim();
if (!word) return;
// Reset UI
loading.style.display = 'flex';
errorDiv.style.display = 'none';
resultDiv.style.display = 'none';
errorResult.style.display = 'none';
const apiKey = localStorage.getItem('groq_api_key') || '';
try {
const resp = await fetch('/api/lookup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ word, language: selectedLanguage, api_key: apiKey }),
});
loading.style.display = 'none';
if (!resp.ok) {
const err = await resp.json();
errorDiv.textContent = err.detail || 'Something went wrong.';
errorDiv.style.display = 'block';
return;
}
const data = await resp.json();
renderResult(data.result);
} catch (e) {
loading.style.display = 'none';
errorDiv.textContent = 'Network error. Is the server running?';
errorDiv.style.display = 'block';
}
}
function renderResult(r) {
// Check if LLM returned an error
if (r.error) {
document.getElementById('resError').textContent = r.error;
errorResult.style.display = 'block';
return;
}
// Word + Phonetic
document.getElementById('resWord').textContent = r.word || '';
document.getElementById('resPhonetic').textContent = r.phonetic || '';
// Transliteration (for non-English)
const transEl = document.getElementById('resTransliteration');
if (r.transliteration) {
transEl.textContent = r.transliteration;
transEl.style.display = 'block';
} else {
transEl.style.display = 'none';
}
// Language badge
document.getElementById('resLanguageBadge').textContent = r.language || selectedLanguage;
// Parts of speech tags
const posContainer = document.getElementById('resPOS');
posContainer.innerHTML = '';
(r.part_of_speech || []).forEach(pos => {
const span = document.createElement('span');
span.className = 'pos-tag';
span.textContent = pos;
posContainer.appendChild(span);
});
// Definitions
const defsContainer = document.getElementById('resDefinitions');
defsContainer.innerHTML = '';
(r.definitions || []).forEach(d => {
const item = document.createElement('div');
item.className = 'definition-item';
item.innerHTML = `
<span class="def-pos">${escapeHtml(d.pos || '')}</span>
<p class="def-meaning">${escapeHtml(d.meaning || '')}</p>
${d.example ? `<p class="def-example">${escapeHtml(d.example)}</p>` : ''}
${d.example_translation ? `<p class="def-example-translation">${escapeHtml(d.example_translation)}</p>` : ''}
`;
defsContainer.appendChild(item);
});
// Synonyms
renderTags('resSynonyms', r.synonyms || []);
document.getElementById('synonymsSection').style.display = (r.synonyms && r.synonyms.length) ? '' : 'none';
// Antonyms
renderTags('resAntonyms', r.antonyms || []);
document.getElementById('antonymsSection').style.display = (r.antonyms && r.antonyms.length) ? '' : 'none';
// Etymology
document.getElementById('resEtymology').textContent = r.etymology || '';
document.getElementById('etymologySection').style.display = r.etymology ? '' : 'none';
// Usage notes
document.getElementById('resUsage').textContent = r.usage_notes || '';
document.getElementById('usageSection').style.display = r.usage_notes ? '' : 'none';
resultDiv.style.display = 'block';
}
function renderTags(containerId, words) {
const container = document.getElementById(containerId);
container.innerHTML = '';
words.forEach(w => {
const span = document.createElement('span');
span.className = 'tag';
span.textContent = w;
span.onclick = () => {
wordInput.value = w;
lookupWord();
};
container.appendChild(span);
});
}
function escapeHtml(text) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(text));
return div.innerHTML;
}
/* ========== Community: Like & Comments ========== */
function getSessionId() {
let id = localStorage.getItem('dict_session_id');
if (!id) {
id = crypto.randomUUID();
localStorage.setItem('dict_session_id', id);
}
return id;
}
async function loadCommunity() {
try {
const sid = getSessionId();
const resp = await fetch(`/api/community?session_id=${encodeURIComponent(sid)}`);
if (!resp.ok) return;
const data = await resp.json();
document.getElementById('likeCount').textContent = data.likes || 0;
const count = data.comments ? data.comments.length : 0;
document.getElementById('commentCount').textContent = `${count} Comment${count !== 1 ? 's' : ''}`;
const btn = document.getElementById('likeBtn');
btn.classList.toggle('liked', !!data.liked);
document.getElementById('likeIcon').textContent = data.liked ? '❤️' : '🤍';
renderComments(data.comments || []);
} catch (_) {}
}
async function toggleLike() {
const btn = document.getElementById('likeBtn');
const isLiked = btn.classList.contains('liked');
try {
const resp = await fetch('/api/like', {
method: isLiked ? 'DELETE' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ session_id: getSessionId() }),
});
if (resp.ok) loadCommunity();
} catch (_) {}
}
function toggleComments() {
const panel = document.getElementById('commentsPanel');
panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}
async function submitComment() {
const nameEl = document.getElementById('commentName');
const textEl = document.getElementById('commentText');
const name = nameEl.value.trim();
const text = textEl.value.trim();
if (!text) return;
try {
const resp = await fetch('/api/comment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: name || 'Anonymous', text }),
});
if (resp.ok) {
textEl.value = '';
loadCommunity();
}
} catch (_) {}
}
function renderComments(comments) {
const list = document.getElementById('commentsList');
if (!comments.length) {
list.innerHTML = '<div class="no-comments">No comments yet. Be the first!</div>';
return;
}
list.innerHTML = comments.map(c => `
<div class="comment-item">
<div class="comment-meta">
<span class="comment-name">${escapeHtml(c.name)}</span>
<span class="comment-time">${escapeHtml(c.time)}</span>
</div>
<div class="comment-text">${escapeHtml(c.text)}</div>
</div>
`).join('');
}
// Load community data on page load
loadCommunity();
|