const STORAGE_KEY = "hvu_qa_history_v1"; const QUESTION_COUNT_LIMITS = { min: 0, max: 100, default: 0 }; const SAMPLE_SNIPPETS = [ { id: "luat-giao-duc-dai-hoc", title: "Luật Giáo dục đại học", preview: "Quy định về cơ sở giáo dục đại học, chương trình đào tạo và quyền tự chủ.", text: "Cơ sở giáo dục đại học có nhiệm vụ tổ chức hoạt động đào tạo, nghiên cứu khoa học, hợp tác quốc tế và phục vụ cộng đồng theo quy định của pháp luật. Cơ sở giáo dục đại học được thực hiện quyền tự chủ gắn với trách nhiệm giải trình, bảo đảm chất lượng đào tạo, công khai điều kiện bảo đảm chất lượng và kết quả hoạt động với cơ quan quản lý nhà nước, người học và xã hội.", suggestedCount: 5, }, { id: "bo-luat-lao-dong", title: "Bộ luật Lao động", preview: "Nội dung về hợp đồng lao động, quyền và nghĩa vụ của người lao động.", text: "Hợp đồng lao động là sự thỏa thuận giữa người lao động và người sử dụng lao động về việc làm có trả công, tiền lương, điều kiện lao động, quyền và nghĩa vụ của mỗi bên. Khi giao kết hợp đồng lao động, các bên phải tuân thủ nguyên tắc tự nguyện, bình đẳng, thiện chí, hợp tác và trung thực; không được thỏa thuận nội dung làm giảm quyền lợi của người lao động so với quy định của pháp luật.", suggestedCount: 4, }, { id: "luat-an-toan-thong-tin-mang", title: "Luật An toàn thông tin mạng", preview: "Yêu cầu bảo vệ thông tin, phòng ngừa rủi ro và trách nhiệm của tổ chức, cá nhân.", text: "Cơ quan, tổ chức, cá nhân tham gia hoạt động trên môi trường mạng có trách nhiệm bảo đảm an toàn thông tin mạng; áp dụng biện pháp quản lý, kỹ thuật phù hợp để phòng ngừa, phát hiện, ngăn chặn và xử lý nguy cơ mất an toàn thông tin. Việc thu thập, xử lý và sử dụng thông tin trên môi trường mạng phải đúng mục đích, đúng thẩm quyền và bảo đảm quyền, lợi ích hợp pháp của cơ quan, tổ chức, cá nhân có liên quan.", suggestedCount: 5, }, ]; const AUTHOR_PROFILES = [ { id: "do-cao-dang", name: "Đỗ Cao Đăng", role: "Sinh viên thực hiện", summary: "Thành viên nhóm thực hiện đề tài.", description: "Sinh viên tham gia triển khai và hoàn thiện hệ thống.", unit: "Khoa Kỹ thuật - Công nghệ", email: "docaodang532001@gmail.com", }, { id: "hoang-tuan-ngoc", name: "Hoàng Tuấn Ngọc", role: "Sinh viên thực hiện", summary: "Thành viên nhóm thực hiện đề tài.", description: "Sinh viên đồng thực hiện và phối hợp phát triển nội dung cho hệ thống.", unit: "Khoa Kỹ thuật - Công nghệ", email: "hoangtuanngoc2005@gmail.com", }, { id: "nguyen-tien-ha", name: "TS. Nguyễn Tiến Hà", role: "Giảng viên hướng dẫn", summary: "Giảng viên hướng dẫn chuyên môn cho đề tài.", description: "Giảng viên hướng dẫn học thuật và định hướng chuyên môn cho đề tài.", unit: "Khoa Kỹ thuật - Công nghệ", email: "nguyentienha@hvu.edu.vn", }, ]; const state = { history: loadHistory(), selectedId: null, thread: [], availableModels: [], activeModelId: "", isSwitchingModel: false, selectedAuthorId: null, isAuthorPanelOpen: false, }; const voiceState = { isSupported: false, isListening: false, recognition: null, discardOnStop: false, stopRequested: false, baseText: "", finalTranscript: "", interimTranscript: "", lastErrorMessage: "", }; const elements = { menuToggle: document.getElementById("menuToggle"), sidebarContent: document.getElementById("sidebarContent"), modelSelect: document.getElementById("modelSelect"), deviceStatus: document.getElementById("deviceStatus"), modelStatus: document.getElementById("modelStatus"), historyList: document.getElementById("historyList"), clearHistory: document.getElementById("clearHistory"), resultCard: document.getElementById("resultCard"), form: document.getElementById("generatorForm"), sourceShell: document.getElementById("sourceShell"), sourceText: document.getElementById("sourceText"), voiceInputButton: document.getElementById("voiceInputButton"), voiceStatus: document.getElementById("voiceStatus"), questionCount: document.getElementById("questionCount"), questionCountValue: document.getElementById("questionCountValue"), decreaseCount: document.getElementById("decreaseCount"), increaseCount: document.getElementById("increaseCount"), generateButton: document.getElementById("generateButton"), authorToggle: document.getElementById("authorToggle"), authorContent: document.getElementById("authorContent"), authorList: document.getElementById("authorList"), copyrightLine: document.getElementById("copyrightLine"), heroTitle: document.getElementById("heroTitle"), landingPanel: document.getElementById("landingPanel"), sampleList: document.getElementById("sampleList"), landingRuntimeBadge: document.getElementById("landingRuntimeBadge"), landingStatusText: document.getElementById("landingStatusText"), landingModelName: document.getElementById("landingModelName"), landingDeviceName: document.getElementById("landingDeviceName"), landingModelCount: document.getElementById("landingModelCount"), }; bootstrap(); function bootstrap() { hydrateQuestionCount(); syncSidebar(false); renderHistory(); renderAuthors(); renderLandingSamples(); attachEvents(); hideResultCard(); activateHeroTitle(); syncCopyright(); autoResizeTextarea(); initVoiceInput(); syncLandingPanel(); fetchInfo(); } function hydrateQuestionCount() { syncQuestionCount(elements.questionCount.value); } function attachEvents() { elements.menuToggle.addEventListener("click", () => { syncSidebar(!document.body.classList.contains("sidebar-open")); }); document.addEventListener("keydown", (event) => { if (event.key === "Escape" && document.body.classList.contains("sidebar-open")) { syncSidebar(false); } }); elements.clearHistory.addEventListener("click", () => { stopVoiceInput(true); state.history = []; state.selectedId = null; state.thread = []; persistHistory(); renderHistory(); hideResultCard(); }); elements.historyList.addEventListener("click", (event) => { const button = event.target.closest("[data-history-id]"); if (!button) return; stopVoiceInput(true); const entry = state.history.find((item) => item.id === button.dataset.historyId); if (!entry) return; state.selectedId = entry.id; state.thread = [entry]; elements.sourceText.value = entry.text || entry.title || ""; autoResizeTextarea(); renderHistory(); renderThread(); }); elements.resultCard.addEventListener("click", async (event) => { const button = event.target.closest("[data-copy-entry-id][data-copy-target]"); if (!button) return; const entryId = button.dataset.copyEntryId; const target = button.dataset.copyTarget; const textToCopy = buildCopyText(entryId, target); if (!textToCopy) return; const copied = await copyToClipboard(textToCopy); if (!copied) return; button.classList.add("is-copied"); button.setAttribute("aria-label", "Đã sao chép"); window.setTimeout(() => { button.classList.remove("is-copied"); button.setAttribute("aria-label", "Sao chép"); }, 1400); }); elements.sourceText.addEventListener("input", () => { autoResizeTextarea(); }); elements.sampleList?.addEventListener("click", (event) => { const button = event.target.closest("[data-sample-id]"); if (!button) return; const sample = SAMPLE_SNIPPETS.find((item) => item.id === button.dataset.sampleId); if (!sample) return; stopVoiceInput(true); elements.sourceText.value = sample.text; if (Number(elements.questionCount.value || QUESTION_COUNT_LIMITS.default) <= 0) { syncQuestionCount(sample.suggestedCount || 5); } autoResizeTextarea(); elements.sourceText.focus(); }); elements.voiceInputButton.addEventListener("click", () => { toggleVoiceInput(); }); elements.modelSelect.addEventListener("change", () => { const nextModelId = String(elements.modelSelect.value || "").trim(); if (!nextModelId || nextModelId === state.activeModelId || state.isSwitchingModel) { return; } switchModel(nextModelId); }); elements.authorToggle?.addEventListener("click", () => { state.isAuthorPanelOpen = !state.isAuthorPanelOpen; renderAuthors(); }); elements.authorList?.addEventListener("click", (event) => { const button = event.target.closest("[data-author-id]"); if (!button) return; selectAuthor(button.dataset.authorId); }); elements.decreaseCount.addEventListener("click", () => { syncQuestionCount(Number(elements.questionCount.value || QUESTION_COUNT_LIMITS.default) - 1); }); elements.increaseCount.addEventListener("click", () => { syncQuestionCount(Number(elements.questionCount.value || QUESTION_COUNT_LIMITS.default) + 1); }); elements.form.addEventListener("submit", async (event) => { event.preventDefault(); if (state.isSwitchingModel) { renderMessage("Vui lòng chờ chuyển model xong rồi thử lại."); return; } if (voiceState.isListening) { renderMessage("Vui lòng dừng micro trước khi sinh câu hỏi."); return; } const text = elements.sourceText.value.trim(); const numQuestions = Number(elements.questionCount.value || String(QUESTION_COUNT_LIMITS.default)); if (!text) { renderMessage("Vui lòng nhập đoạn văn bản trước khi sinh câu hỏi."); elements.sourceText.focus(); return; } if (numQuestions <= 0) { renderMessage("Vui lòng tăng số câu hỏi lên ít nhất 1."); elements.increaseCount.focus(); return; } const pendingEntry = { id: makeId(), title: shrink(text, 52), text, questions: [], elapsedMs: null, device: null, count: numQuestions, createdAt: new Date().toISOString(), status: "pending", errorMessage: "", }; state.thread = [...state.thread, pendingEntry]; renderThread(); elements.sourceText.value = ""; autoResizeTextarea(); setLoading(true); try { const response = await fetch("/api/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model_id: state.activeModelId || undefined, text, num_questions: numQuestions, }), }); const payload = await response.json(); if (!response.ok || !payload.ok) { throw new Error(payload.error || "Không thể sinh câu hỏi lúc này."); } const entry = { id: pendingEntry.id, title: shrink(text, 52), text: payload.text, questions: payload.questions, elapsedMs: payload.elapsed_ms, device: payload.meta.active_device || payload.meta.predicted_device, count: payload.questions?.length || numQuestions, createdAt: pendingEntry.createdAt, status: "done", errorMessage: "", }; state.selectedId = entry.id; state.history = [entry, ...state.history.filter((item) => item.questions?.length)].slice(0, 10); state.thread = state.thread.map((item) => (item.id === pendingEntry.id ? entry : item)); persistHistory(); renderHistory(); renderThread(); } catch (error) { state.thread = state.thread.map((item) => item.id === pendingEntry.id ? { ...item, status: "error", errorMessage: error.message || "Có lỗi xảy ra khi sinh câu hỏi.", } : item, ); renderThread(); } finally { setLoading(false); } }); } function syncQuestionCount(value) { const parsedValue = Number(value); const normalizedValue = Number.isFinite(parsedValue) ? Math.trunc(parsedValue) : QUESTION_COUNT_LIMITS.default; const safeValue = Math.min( QUESTION_COUNT_LIMITS.max, Math.max(QUESTION_COUNT_LIMITS.min, normalizedValue), ); const isLoading = isInterfaceBusy(); elements.questionCount.value = String(safeValue); elements.questionCountValue.textContent = String(safeValue); elements.decreaseCount.disabled = isLoading || safeValue <= QUESTION_COUNT_LIMITS.min; elements.increaseCount.disabled = isLoading || safeValue >= QUESTION_COUNT_LIMITS.max; } function syncSidebar(isOpen) { document.body.classList.toggle("sidebar-open", isOpen); elements.menuToggle.setAttribute("aria-expanded", String(isOpen)); elements.sidebarContent.setAttribute("aria-hidden", String(!isOpen)); } function initVoiceInput() { const SpeechRecognitionApi = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SpeechRecognitionApi) { voiceState.isSupported = false; syncVoiceUi(buildVoiceUnsupportedMessage(), "error"); return; } if (!canUseBrowserVoiceInput()) { voiceState.isSupported = false; syncVoiceUi(buildVoiceOriginMessage(), "error"); return; } voiceState.recognition = createSpeechRecognition(SpeechRecognitionApi); voiceState.isSupported = true; syncVoiceUi(""); } function toggleVoiceInput() { if (!voiceState.isSupported) { syncVoiceUi( canUseBrowserVoiceInput() ? buildVoiceUnsupportedMessage() : buildVoiceOriginMessage(), "error", ); return; } if (voiceState.isListening) { stopVoiceInput(false); return; } startVoiceInput(); } function startVoiceInput() { if (!voiceState.recognition) { syncVoiceUi(buildVoiceUnsupportedMessage(), "error"); return; } try { voiceState.baseText = elements.sourceText.value.trimEnd(); voiceState.finalTranscript = ""; voiceState.interimTranscript = ""; voiceState.discardOnStop = false; voiceState.stopRequested = false; voiceState.lastErrorMessage = ""; syncVoiceUi("Đang bật nhận giọng nói..."); voiceState.recognition.start(); } catch (error) { voiceState.discardOnStop = false; syncVoiceUi(humanizeVoiceStartError(error), "error"); } } function stopVoiceInput(discardRecording = false) { if (!voiceState.isListening || !voiceState.recognition) { return; } voiceState.discardOnStop = Boolean(discardRecording); voiceState.stopRequested = true; if (discardRecording) { voiceState.finalTranscript = ""; voiceState.interimTranscript = ""; elements.sourceText.value = voiceState.baseText; autoResizeTextarea(); } syncVoiceUi(discardRecording ? "Đang hủy nhận giọng nói..." : "Đang dừng micro..."); voiceState.recognition.stop(); } function createSpeechRecognition(SpeechRecognitionApi) { const recognition = new SpeechRecognitionApi(); recognition.lang = "vi-VN"; recognition.continuous = true; recognition.interimResults = true; recognition.maxAlternatives = 1; recognition.onstart = () => { voiceState.isListening = true; voiceState.stopRequested = false; voiceState.lastErrorMessage = ""; syncVoiceUi("Đang nghe... hãy nói vào micro."); }; recognition.onresult = (event) => { if (voiceState.discardOnStop) { return; } let nextFinalTranscript = ""; let nextInterimTranscript = ""; for (let index = event.resultIndex; index < event.results.length; index += 1) { const transcript = String(event.results[index][0]?.transcript || "").trim(); if (!transcript) continue; if (event.results[index].isFinal) { nextFinalTranscript = appendSpeechChunk(nextFinalTranscript, transcript); } else { nextInterimTranscript = appendSpeechChunk(nextInterimTranscript, transcript); } } if (nextFinalTranscript) { voiceState.finalTranscript = appendSpeechChunk(voiceState.finalTranscript, nextFinalTranscript); } voiceState.interimTranscript = nextInterimTranscript; syncSpeechDraft(); syncVoiceUi("Đang nghe... bấm lại nếu muốn dừng."); }; recognition.onerror = (event) => { console.warn("SpeechRecognition error:", event.error); if (event.error === "aborted" && (voiceState.discardOnStop || voiceState.stopRequested)) { voiceState.lastErrorMessage = ""; return; } voiceState.lastErrorMessage = humanizeVoiceRecognitionError(event.error); }; recognition.onend = () => { const shouldDiscard = voiceState.discardOnStop; const recognizedText = appendSpeechChunk(voiceState.finalTranscript, voiceState.interimTranscript); const hasRecognizedText = Boolean(recognizedText.trim()); voiceState.isListening = false; if (!shouldDiscard && hasRecognizedText) { elements.sourceText.value = appendSpeechChunk(voiceState.baseText, recognizedText); autoResizeTextarea(); } let finalMessage = ""; let finalTone = "default"; if (voiceState.lastErrorMessage) { finalMessage = voiceState.lastErrorMessage; finalTone = "error"; } else if (!shouldDiscard && hasRecognizedText) { finalMessage = "Đã chèn nội dung giọng nói vào ô nhập."; } else if (!shouldDiscard && !voiceState.stopRequested) { finalMessage = "Không nhận diện được nội dung giọng nói. Hãy thử lại."; finalTone = "error"; } voiceState.discardOnStop = false; voiceState.stopRequested = false; voiceState.finalTranscript = ""; voiceState.interimTranscript = ""; voiceState.lastErrorMessage = ""; voiceState.baseText = elements.sourceText.value.trimEnd(); syncVoiceUi(finalMessage, finalTone); }; return recognition; } function appendSpeechChunk(base, chunk) { const normalizedBase = String(base || ""); const normalizedChunk = String(chunk || "").trim(); if (!normalizedChunk) return normalizedBase; if (!normalizedBase.trim()) return normalizedChunk; return /[\s(]$/.test(normalizedBase) ? `${normalizedBase}${normalizedChunk}` : `${normalizedBase} ${normalizedChunk}`; } function humanizeVoiceStartError(error) { const errorName = error?.name || ""; if (errorName === "InvalidStateError") { return "Micro đang hoạt động. Hãy dừng phiên hiện tại trước khi bật lại."; } if (errorName === "NotAllowedError" || errorName === "SecurityError") { if (!canUseBrowserVoiceInput()) { return buildVoiceOriginMessage(); } return "Bạn chưa cấp quyền micro cho trình duyệt."; } if (errorName === "NotFoundError" || errorName === "DevicesNotFoundError") { return "Không tìm thấy thiết bị micro."; } return "Không thể bật nhận giọng nói lúc này. Hãy thử lại."; } function humanizeVoiceRecognitionError(errorCode) { if (errorCode === "not-allowed" || errorCode === "service-not-allowed") { if (!canUseBrowserVoiceInput()) { return buildVoiceOriginMessage(); } return "Bạn chưa cấp quyền micro hoặc nhận giọng nói cho trình duyệt."; } if (errorCode === "audio-capture") { return "Không tìm thấy micro hoặc micro đang bị chiếm dụng."; } if (errorCode === "network") { if (!navigator.onLine) { return "Thiết bị đang offline. Hãy kết nối Internet rồi thử lại."; } if (!canUseBrowserVoiceInput()) { return buildVoiceOriginMessage(); } return "Trình duyệt không kết nối được dịch vụ nhận giọng nói. Hãy dùng Chrome hoặc Edge, kiểm tra mạng, VPN hay firewall rồi thử lại."; } if (errorCode === "language-not-supported") { return "Trình duyệt không hỗ trợ nhận giọng nói tiếng Việt."; } if (errorCode === "no-speech") { return "Không nghe thấy giọng nói. Hãy thử nói gần micro hơn."; } return "Không thể nhận giọng nói lúc này. Hãy thử lại."; } function canUseBrowserVoiceInput() { return window.isSecureContext || isLocalhost(window.location.hostname); } function isLocalhost(hostname) { return ( hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]" ); } function buildVoiceUnsupportedMessage() { return "Trình duyệt này chưa hỗ trợ nhập giọng nói trực tiếp. Hãy dùng Chrome hoặc Edge bản mới."; } function buildVoiceOriginMessage() { return "Nhập bằng giọng nói qua trình duyệt chỉ hoạt động trên HTTPS hoặc localhost. Hãy mở ứng dụng bằng https:// hoặc http://localhost."; } function syncSpeechDraft() { const stableText = appendSpeechChunk(voiceState.baseText, voiceState.finalTranscript); elements.sourceText.value = appendSpeechChunk(stableText, voiceState.interimTranscript); autoResizeTextarea(); } function syncVoiceUi(message, tone = "default") { const resolvedMessage = String(message || "").trim(); elements.voiceStatus.textContent = resolvedMessage; elements.voiceStatus.classList.toggle("is-empty", !resolvedMessage); elements.voiceStatus.classList.toggle("is-error", tone === "error"); elements.voiceStatus.classList.toggle("is-active", voiceState.isListening); elements.voiceInputButton.disabled = !voiceState.isSupported; elements.voiceInputButton.classList.toggle("is-listening", voiceState.isListening); elements.voiceInputButton.classList.toggle("is-unsupported", !voiceState.isSupported); elements.voiceInputButton.setAttribute( "aria-label", voiceState.isListening ? "Dừng nhận giọng nói" : "Nhập bằng giọng nói qua trình duyệt", ); } function autoResizeTextarea() { const collapsedHeight = 30; const expandedMinHeight = 86; const hasContent = elements.sourceText.value.trim().length > 0; elements.sourceText.style.height = `${collapsedHeight}px`; const nextHeight = Math.min(elements.sourceText.scrollHeight, 240); elements.sourceText.style.height = `${Math.max(nextHeight, hasContent ? expandedMinHeight : collapsedHeight)}px`; elements.sourceShell.classList.toggle("is-expanded", hasContent || nextHeight > collapsedHeight + 4); } function loadHistory() { try { const saved = window.localStorage.getItem(STORAGE_KEY); if (!saved) { return []; } const parsed = JSON.parse(saved); if (!Array.isArray(parsed)) return []; return parsed .map((item) => ({ ...item, id: item.id || makeId(), createdAt: item.createdAt || new Date().toISOString(), })) .filter((item) => Array.isArray(item.questions) && item.questions.length > 0); } catch { return []; } } function persistHistory() { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state.history)); } async function fetchInfo() { try { const response = await fetch("/api/info"); const payload = await response.json(); if (!response.ok || !payload.ok) { throw new Error(payload.error || "Không đọc được thông tin hệ thống."); } applySystemInfo(payload); } catch (error) { state.availableModels = []; state.activeModelId = ""; renderModelOptions("Không tải được danh sách model."); elements.deviceStatus.textContent = "Không kết nối được backend."; elements.modelStatus.textContent = error.message || "Vui lòng kiểm tra lại backend hoặc server Flask."; syncLandingStatus({ modelName: "Không tải được danh sách model", deviceName: "Chưa kết nối backend", modelCount: 0, badgeText: "Lỗi kết nối", badgeTone: "error", statusText: error.message || "Không thể đọc thông tin hệ thống từ backend.", }); } } async function switchModel(modelId) { const previousModelId = state.activeModelId; state.isSwitchingModel = true; syncInteractiveControls(); elements.modelStatus.textContent = "Đang chuyển model..."; syncLandingStatus({ modelName: state.availableModels.find((item) => item.id === modelId)?.label || "Đang chuyển model...", deviceName: elements.deviceStatus.textContent || "Đang kiểm tra...", modelCount: state.availableModels.length, badgeText: "Đang chuyển", badgeTone: "pending", statusText: "Hệ thống đang chuyển model theo lựa chọn của bạn.", }); try { const response = await fetch("/api/model", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model_id: modelId }), }); const payload = await response.json(); if (!response.ok || !payload.ok) { throw new Error(payload.error || "Không thể chuyển model lúc này."); } applySystemInfo(payload); } catch (error) { state.activeModelId = previousModelId; renderModelOptions(); elements.modelStatus.textContent = error.message || "Không thể chuyển model lúc này."; syncLandingStatus({ modelName: state.availableModels.find((item) => item.id === previousModelId)?.label || state.availableModels[0]?.label || "Không xác định", deviceName: elements.deviceStatus.textContent || "Đang kiểm tra...", modelCount: state.availableModels.length, badgeText: "Lỗi chuyển model", badgeTone: "error", statusText: error.message || "Không thể chuyển model lúc này.", }); } finally { state.isSwitchingModel = false; syncInteractiveControls(); } } function applySystemInfo(payload) { const availableModels = Array.isArray(payload.available_models) ? payload.available_models : []; const fallbackModelId = String(payload.selected_model_id || payload.model_name || "default-model"); const fallbackModelLabel = String(payload.model_name || "Model hiện tại"); state.availableModels = availableModels.length ? availableModels : [{ id: fallbackModelId, label: fallbackModelLabel }]; state.activeModelId = String(payload.selected_model_id || state.availableModels[0]?.id || ""); renderModelOptions(); const activeModel = state.availableModels.find((item) => item.id === state.activeModelId)?.label || payload.model_name || "Model"; elements.deviceStatus.textContent = humanizeDevice(payload.meta.active_device || payload.meta.predicted_device); elements.modelStatus.textContent = payload.meta.loaded ? `${activeModel} đã sẵn sàng cho tác vụ sinh câu hỏi.` : `Đã chọn ${activeModel}. Model sẽ được nạp tự động ở lần sinh câu hỏi đầu tiên.`; syncLandingStatus({ modelName: activeModel, deviceName: humanizeDeviceCompact(payload.meta.active_device || payload.meta.predicted_device), modelCount: state.availableModels.length, badgeText: payload.meta.loaded ? "Sẵn sàng" : "Chờ nạp model", badgeTone: payload.meta.loaded ? "ready" : "pending", statusText: payload.meta.loaded ? `${activeModel} đã nạp xong và có thể sử dụng ngay.` : `${activeModel} sẽ được nạp tự động ở lần sinh câu hỏi đầu tiên.`, }); } function renderModelOptions(emptyLabel = "Chưa có model khả dụng.") { elements.modelSelect.innerHTML = ""; if (!state.availableModels.length) { const fallbackOption = document.createElement("option"); fallbackOption.value = ""; fallbackOption.textContent = emptyLabel; elements.modelSelect.appendChild(fallbackOption); elements.modelSelect.disabled = true; return; } for (const model of state.availableModels) { const option = document.createElement("option"); option.value = model.id; option.textContent = model.label; elements.modelSelect.appendChild(option); } if (!state.availableModels.some((item) => item.id === state.activeModelId)) { state.activeModelId = state.availableModels[0].id; } elements.modelSelect.value = state.activeModelId; syncInteractiveControls(); } function renderAuthors() { if (!elements.authorToggle || !elements.authorContent || !elements.authorList) return; elements.authorToggle.setAttribute("aria-expanded", String(state.isAuthorPanelOpen)); elements.authorToggle.classList.toggle("is-open", state.isAuthorPanelOpen); elements.authorContent.hidden = !state.isAuthorPanelOpen; if (!state.isAuthorPanelOpen) { elements.authorList.innerHTML = ""; return; } elements.authorList.innerHTML = AUTHOR_PROFILES.map((author) => { const isActive = author.id === state.selectedAuthorId; const detailMarkup = isActive ? buildAuthorDetailMarkup(author) : ""; return `
${detailMarkup}
`; }).join(""); } function renderLandingSamples() { if (!elements.sampleList) return; elements.sampleList.innerHTML = SAMPLE_SNIPPETS.map((sample) => ` `).join(""); } function syncLandingPanel() { if (!elements.landingPanel) return; elements.landingPanel.hidden = !elements.resultCard.hidden; } function syncLandingStatus({ modelName = "Đang tải...", deviceName = "Đang kiểm tra...", modelCount = 0, badgeText = "Đang kiểm tra", badgeTone = "pending", statusText = "Đang đồng bộ trạng thái hệ thống.", } = {}) { if ( !elements.landingRuntimeBadge || !elements.landingStatusText || !elements.landingModelName || !elements.landingDeviceName || !elements.landingModelCount ) { return; } elements.landingRuntimeBadge.textContent = badgeText; elements.landingRuntimeBadge.classList.remove("is-ready", "is-pending", "is-error"); elements.landingRuntimeBadge.classList.add( badgeTone === "ready" ? "is-ready" : badgeTone === "error" ? "is-error" : "is-pending", ); elements.landingStatusText.textContent = statusText; elements.landingModelName.textContent = modelName; elements.landingDeviceName.textContent = deviceName; elements.landingModelCount.textContent = String(modelCount); } function selectAuthor(authorId) { if (!AUTHOR_PROFILES.some((author) => author.id === authorId)) { return; } state.selectedAuthorId = state.selectedAuthorId === authorId ? null : authorId; renderAuthors(); } function buildAuthorDetailMarkup(author) { const metaItems = [ { label: "Vai trò", value: author.description }, { label: "Đơn vị", value: author.unit }, ...(author.email ? [{ label: "Email", value: author.email }] : []), ]; return `
${metaItems .map( (item) => `
${escapeHtml(item.label)} ${escapeHtml(item.value)}
`, ) .join("")}
`; } function humanizeDevice(device) { if (device === "cuda") return "Đang sử dụng GPU CUDA."; return "Đang sử dụng CPU."; } function humanizeDeviceCompact(device) { if (device === "cuda") return "GPU CUDA"; return "CPU"; } function renderHistory() { if (!state.history.length) { elements.historyList.innerHTML = '
Chưa có lịch sử. Hãy tạo bộ câu hỏi đầu tiên của bạn.
'; return; } elements.historyList.innerHTML = state.history .map((item) => { const activeClass = item.id === state.selectedId ? "is-active" : ""; return ` `; }) .join(""); } function showResultCard() { elements.resultCard.hidden = false; elements.resultCard.classList.add("is-visible"); syncLandingPanel(); } function hideResultCard() { elements.resultCard.hidden = true; elements.resultCard.classList.remove("is-visible"); elements.resultCard.classList.remove("has-entry"); elements.resultCard.classList.remove("is-updating"); elements.resultCard.innerHTML = ""; syncLandingPanel(); } function renderMessage(message) { showResultCard(); elements.resultCard.classList.remove("is-updating"); if (state.thread.length) { elements.resultCard.classList.add("has-entry"); elements.resultCard.innerHTML = `

${escapeHtml(message)}

${renderThreadMarkup(state.thread)} `; return; } elements.resultCard.classList.remove("has-entry"); elements.resultCard.innerHTML = `

${escapeHtml(message)}

`; } function renderThread() { if (!state.thread.length) { hideResultCard(); return; } showResultCard(); elements.resultCard.classList.add("has-entry"); elements.resultCard.classList.remove("is-updating"); elements.resultCard.innerHTML = renderThreadMarkup(state.thread); } function renderThreadMarkup(entries) { return `
${entries.map((entry) => renderThreadItem(entry)).join("")}
`; } function renderThreadItem(entry) { const questions = Array.isArray(entry.questions) ? entry.questions : []; const questionItems = questions.map((item) => `
  • ${escapeHtml(item)}
  • `).join(""); const statusLabel = entry.status === "pending" ? "ĐANG XỬ LÝ" : entry.status === "error" ? "LỖI" : entry.device ? entry.device.toUpperCase() : "AUTO"; const questionBlock = entry.status === "pending" ? `

    Đang sinh câu hỏi từ đoạn văn bản này...

    ` : entry.status === "error" ? `

    ${escapeHtml(entry.errorMessage || "Có lỗi xảy ra khi sinh câu hỏi.")}

    ` : questions.length ? `
      ${questionItems}
    ` : '

    Mục lịch sử này chưa lưu danh sách câu hỏi. Hãy bấm “Sinh câu hỏi” để tạo lại.

    '; return `
    ${escapeHtml(formatTimestamp(entry.createdAt))} ${escapeHtml(statusLabel)} ${escapeHtml(String(entry.count || questions.length || 0))} câu hỏi ${entry.elapsedMs ? `${escapeHtml(String(entry.elapsedMs))} ms` : ""}

    Văn bản đầu vào

    ${escapeHtml(entry.text || entry.title || "")}

    Câu hỏi sinh ra

    ${questionBlock}
    `; } function copyIconMarkup() { return ` `; } function buildCopyText(entryId, target) { const entry = state.thread.find((item) => item.id === entryId) || state.history.find((item) => item.id === entryId); if (!entry) return ""; if (target === "source") { return String(entry.text || entry.title || "").trim(); } if (entry.status === "pending") { return "Đang sinh câu hỏi từ đoạn văn bản này..."; } if (entry.status === "error") { return String(entry.errorMessage || "Có lỗi xảy ra khi sinh câu hỏi.").trim(); } const questions = Array.isArray(entry.questions) ? entry.questions : []; if (questions.length) { return questions.map((item, index) => `${index + 1}. ${item}`).join("\n"); } return "Mục lịch sử này chưa lưu danh sách câu hỏi. Hãy bấm “Sinh câu hỏi” để tạo lại."; } async function copyToClipboard(text) { try { await navigator.clipboard.writeText(text); return true; } catch { try { const area = document.createElement("textarea"); area.value = text; area.setAttribute("readonly", ""); area.style.position = "fixed"; area.style.opacity = "0"; document.body.appendChild(area); area.select(); const success = document.execCommand("copy"); area.remove(); return success; } catch { return false; } } } function setLoading(isLoading) { elements.generateButton.classList.toggle("is-loading", isLoading); document.body.classList.toggle("is-generating", isLoading); elements.resultCard.classList.toggle("is-updating", isLoading && elements.resultCard.classList.contains("has-entry")); syncQuestionCount(elements.questionCount.value); syncInteractiveControls(); } function isInterfaceBusy() { return document.body.classList.contains("is-generating") || state.isSwitchingModel; } function syncInteractiveControls() { const isBusy = isInterfaceBusy(); elements.generateButton.disabled = isBusy; elements.modelSelect.disabled = isBusy || state.availableModels.length <= 1; } function activateHeroTitle() { const node = elements.heroTitle; if (!node) return; const fullText = String(node.dataset.text || "").trim(); if (!fullText) return; node.textContent = fullText; node.classList.remove("is-ready"); if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { node.classList.add("is-ready"); return; } window.requestAnimationFrame(() => { node.classList.add("is-ready"); }); } function shrink(text, maxLength) { const normalized = String(text || "").trim(); if (normalized.length <= maxLength) return normalized; return `${normalized.slice(0, maxLength - 3).trim()}...`; } function formatTimestamp(value) { const date = new Date(value); if (Number.isNaN(date.getTime())) return "Vừa xong"; const now = new Date(); const sameDay = date.toDateString() === now.toDateString(); const yesterday = new Date(now); yesterday.setDate(now.getDate() - 1); const timeLabel = date.toLocaleTimeString("vi-VN", { hour: "2-digit", minute: "2-digit" }); if (sameDay) return `Hôm nay ${timeLabel}`; if (date.toDateString() === yesterday.toDateString()) return `Hôm qua ${timeLabel}`; return date.toLocaleDateString("vi-VN", { day: "2-digit", month: "2-digit", year: "numeric" }); } function syncCopyright() { const year = new Date().getFullYear(); elements.copyrightLine.textContent = `© ${year} HVU - KTCN`; } function escapeHtml(value) { return String(value || "") .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); } function makeId() { if (window.crypto && typeof window.crypto.randomUUID === "function") { return window.crypto.randomUUID(); } return `item-${Date.now()}-${Math.random().toString(16).slice(2)}`; }