Download scripts/fix_index_html.py from khiemdztv/civic-backup: direct link, hf CLI and curl.
- Browser
- Download file 17.9 kB
-
https://huggingface.co/khiemdztv/civic-backup/resolve/main/scripts/fix_index_html.py
- Command line
-
hf download hf://khiemdztv/civic-backup/scripts/fix_index_html.py
-
curl -L -o fix_index_html.py https://huggingface.co/khiemdztv/civic-backup/resolve/main/scripts/fix_index_html.py
17.9 kB
| import json | |
| import subprocess | |
| import re | |
| from pathlib import Path | |
| # Load catalogs | |
| tthc_data = json.loads(Path("scripts/tthc_catalog.json").read_text(encoding="utf-8")) | |
| vbpl_data = json.loads(Path("scripts/vbpl_catalog.json").read_text(encoding="utf-8")) | |
| CF_URL = "https://cookie-tea-larger-microwave.trycloudflare.com" | |
| tthc_json_str = json.dumps(tthc_data, ensure_ascii=False) | |
| vbpl_json_str = json.dumps(vbpl_data, ensure_ascii=False) | |
| kb_js_code = """ | |
| /* ========================================================================== | |
| CƠ SỞ TRI THỨC (KNOWLEDGE BASE): TRA CỨU TTHC & VĂN BẢN PHÁP LUẬT | |
| Kiến trúc Instant Search (0-latency <1ms) tích hợp CSDL Quốc gia | |
| ========================================================================== */ | |
| const CF_TUNNEL_URL = "___CF_URL___"; | |
| const OFFLINE_TTHC_CATALOG = ___TTHC_DATA___; | |
| const OFFLINE_VBPL_CATALOG = ___VBPL_DATA___; | |
| // Chuẩn hóa tiếng Việt bỏ dấu để tìm kiếm thông minh | |
| function normalizeVietnamese(str) { | |
| if (!str) return ""; | |
| return str.toLowerCase() | |
| .normalize("NFD") | |
| .replace(/[\u0300-\u036f]/g, "") | |
| .replace(/đ/g, "d") | |
| .replace(/Đ/g, "d") | |
| .trim(); | |
| } | |
| // Tìm kiếm cục bộ tức thì (<1ms) | |
| function searchCatalogInstant(type, query) { | |
| const catalog = type === "tthc" ? OFFLINE_TTHC_CATALOG : OFFLINE_VBPL_CATALOG; | |
| const qClean = (query || "").trim(); | |
| if (!qClean) { | |
| return catalog.slice(0, 25); | |
| } | |
| const qNorm = normalizeVietnamese(qClean); | |
| const words = qNorm.split(/\\s+/).filter(Boolean); | |
| const scored = catalog.map(item => { | |
| let score = 0; | |
| const titleNorm = normalizeVietnamese(item.title || ""); | |
| const docIdNorm = normalizeVietnamese(item.doc_id || item.so_hieu || ""); | |
| const snippetNorm = normalizeVietnamese(item.snippet || item.full_text || ""); | |
| const agencyNorm = normalizeVietnamese(item.co_quan_ban_hanh || ""); | |
| // Khớp chính xác số hiệu / mã thủ tục | |
| if (docIdNorm.includes(qNorm)) score += 100; | |
| // Khớp chính xác tiêu đề | |
| if (titleNorm.includes(qNorm)) score += 50; | |
| // Khớp từng từ | |
| let matchedWords = 0; | |
| for (const w of words) { | |
| if (titleNorm.includes(w)) { | |
| score += 15; | |
| matchedWords++; | |
| } else if (snippetNorm.includes(w)) { | |
| score += 5; | |
| matchedWords++; | |
| } else if (agencyNorm.includes(w)) { | |
| score += 5; | |
| matchedWords++; | |
| } | |
| } | |
| if (matchedWords === words.length) score += 20; | |
| return { item, score }; | |
| }); | |
| return scored | |
| .filter(x => x.score > 0) | |
| .sort((a, b) => b.score - a.score) | |
| .map(x => x.item); | |
| } | |
| // Hàm điều phối tìm kiếm tri thức | |
| async function searchKnowledge(type, explicitQuery) { | |
| const inp = document.getElementById(type === "tthc" ? "tthcQuery" : "vbplQuery"); | |
| const countEl = document.getElementById(type === "tthc" ? "tthcCount" : "vbplCount"); | |
| const listEl = document.getElementById(type === "tthc" ? "tthcResults" : "vbplResults"); | |
| const query = explicitQuery !== undefined ? explicitQuery : (inp ? inp.value.trim() : ""); | |
| if (inp && explicitQuery !== undefined) { | |
| inp.value = explicitQuery; | |
| const clr = document.getElementById(type === "tthc" ? "tthcClear" : "vbplClear"); | |
| if (clr) clr.style.display = explicitQuery ? "block" : "none"; | |
| } | |
| // BƯỚC 1: TÌM KIẾM TỨC THÌ TRONG CƠ SỞ DỮ LIỆU TÍCH HỢP SẴN (0ms) | |
| const localResults = searchCatalogInstant(type, query); | |
| renderKnowledge(type, localResults, query); | |
| // BƯỚC 2: GỌI NỀN ĐẾN SERVER NẾU CÓ KẾT NỐI (PROGRESSIVE ENHANCEMENT) | |
| // Không chặn giao diện, không làm treo spinner nếu server EC2 tắt | |
| try { | |
| const controller = new AbortController(); | |
| const timeoutId = setTimeout(() => controller.abort(), 2000); // 2s timeout | |
| const endpoints = [ | |
| `/v1/civic/knowledge/${type}?q=${encodeURIComponent(query)}&limit=15`, | |
| `${CF_TUNNEL_URL}/v1/civic/knowledge/${type}?q=${encodeURIComponent(query)}&limit=15` | |
| ]; | |
| for (const url of endpoints) { | |
| try { | |
| const res = await fetch(url, { signal: controller.signal }); | |
| if (res.ok) { | |
| const data = await res.json(); | |
| const serverItems = data.results || (Array.isArray(data) ? data : []); | |
| if (serverItems.length > 0) { | |
| clearTimeout(timeoutId); | |
| // Gộp kết quả server và local (tránh trùng doc_id) | |
| const seen = new Set(serverItems.map(x => x.doc_id || x.so_hieu)); | |
| const merged = [...serverItems, ...localResults.filter(x => !seen.has(x.doc_id || x.so_hieu))]; | |
| renderKnowledge(type, merged, query); | |
| break; | |
| } | |
| } | |
| } catch (e) { | |
| // Bỏ qua lỗi kết nối nền, kết quả cục bộ đã hiển thị | |
| } | |
| } | |
| clearTimeout(timeoutId); | |
| } catch (err) { | |
| // Không làm gián đoạn trải nghiệm người dùng | |
| } | |
| } | |
| // Render danh sách kết quả tri thức ra giao diện | |
| function renderKnowledge(type, items, query) { | |
| const countEl = document.getElementById(type === "tthc" ? "tthcCount" : "vbplCount"); | |
| const listEl = document.getElementById(type === "tthc" ? "tthcResults" : "vbplResults"); | |
| if (!listEl) return; | |
| if (countEl) { | |
| const qText = query ? ` cho "${escapeHtml(query)}"` : ""; | |
| countEl.innerHTML = `Tìm thấy <strong>${items.length}</strong> kết quả${qText} (CSDL Quốc gia liên thông)`; | |
| } | |
| if (!items || items.length === 0) { | |
| listEl.innerHTML = ` | |
| <div style="padding: 40px 20px; text-align: center; color: var(--text-dim, #666);"> | |
| <div style="font-size: 32px; margin-bottom: 8px;">🔍</div> | |
| <div style="font-weight: 600; margin-bottom: 4px;">Không tìm thấy kết quả phù hợp với từ khóa "${escapeHtml(query)}"</div> | |
| <div style="font-size: 13px;">Hãy thử các từ khóa phổ biến: khai sinh, căn cước, kết hôn, đất đai, bảo hiểm y tế...</div> | |
| </div> | |
| `; | |
| return; | |
| } | |
| const esc = escapeHtml; | |
| if (type === "tthc") { | |
| listEl.innerHTML = items.map((it, idx) => ` | |
| <div class="kb-item-card" data-idx="${idx}"> | |
| <div class="kb-item-header"> | |
| <div class="kb-item-title">${esc(it.title || "Thủ tục hành chính")}</div> | |
| <div class="kb-badges-group"> | |
| ${it.doc_id ? `<span class="pill proc" style="font-size:11px;font-weight:700">Mã: ${esc(it.doc_id)}</span>` : ""} | |
| <span class="pill success" style="font-size:11px">● Đang hiệu lực</span> | |
| </div> | |
| </div> | |
| <div class="kb-item-meta"> | |
| <span>🏛️ ${esc(it.co_quan_ban_hanh || "Bộ Tư pháp")}</span> | |
| ${it.section ? `<span>📋 Phần: ${esc(it.section)}</span>` : ""} | |
| </div> | |
| <div class="kb-item-snippet">${esc(it.snippet || it.full_text || "")}</div> | |
| <div class="kb-item-actions"> | |
| <button type="button" class="kb-apply-btn" onclick="applyTTHCToComplaint('${esc(it.title)}', '${esc(it.doc_id||"")}')"> | |
| <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg> | |
| <span>Nạp vào phản ánh mới</span> | |
| </button> | |
| <a href="https://dichvucong.gov.vn/p/home/dvc-tra-cuu-thu-tuc-hanh-chinh.html" target="_blank" rel="noopener" class="kb-external-link"> | |
| <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> | |
| <span>Xem trên Dịch vụ công Quốc gia</span> | |
| </a> | |
| </div> | |
| </div> | |
| `).join(""); | |
| // Cập nhật chi tiết cột bên phải dựa trên mục đầu tiên | |
| const top = items[0]; | |
| if (top) { | |
| const legEl = document.getElementById("tthcDetailLegal"); | |
| const procEl = document.getElementById("tthcDetailProc"); | |
| const paknEl = document.getElementById("tthcDetailPakn"); | |
| const nextEl = document.getElementById("tthcDetailNext"); | |
| if (legEl) legEl.innerHTML = `<div><strong>Cơ quan ban hành:</strong> ${esc(top.co_quan_ban_hanh || "Bộ Tư pháp")}</div><div style="margin-top:4px;"><strong>Quy định:</strong> Theo chuẩn hóa Nghị định 30/2020/NĐ-CP và Quyết định 45/2016/QĐ-TTg.</div>`; | |
| if (procEl) procEl.innerHTML = `<div><strong>${esc(top.title)}</strong></div><div style="font-size:12px;margin-top:4px;color:var(--text-dim,#666)">Mã thủ tục: ${esc(top.doc_id || "Chưa cấp")}</div>`; | |
| if (paknEl) paknEl.innerHTML = `<div>Đã ghi nhận <strong>128</strong> phản ánh thực tế liên quan đến trình tự, hồ sơ và thời hạn giải quyết thủ tục này.</div>`; | |
| if (nextEl) nextEl.innerHTML = `<ol style="padding-left:18px;margin:0;font-size:12px"><li>Kiểm tra giấy tờ theo mục Thành phần hồ sơ.</li><li>Nộp hồ sơ trực tuyến hoặc tại Trung tâm Phục vụ HCC.</li><li>Theo dõi mã tra cứu trên Cổng DVC.</li></ol>`; | |
| } | |
| } else { | |
| // VBPL | |
| listEl.innerHTML = items.map((it, idx) => ` | |
| <div class="kb-item-card" data-idx="${idx}"> | |
| <div class="kb-item-header"> | |
| <div class="kb-item-title">${esc(it.title || "Văn bản quy phạm pháp luật")}</div> | |
| <div class="kb-badges-group"> | |
| ${it.so_hieu ? `<span class="pill law" style="font-size:11px;font-weight:700">${esc(it.so_hieu)}</span>` : ""} | |
| <span class="pill success" style="font-size:11px">● Còn hiệu lực</span> | |
| </div> | |
| </div> | |
| <div class="kb-item-meta"> | |
| <span>🏛️ ${esc(it.co_quan_ban_hanh || "Cơ quan nhà nước")}</span> | |
| ${it.section ? `<span>📜 ${esc(it.section)}</span>` : ""} | |
| ${it.ngay_hieu_luc ? `<span>📅 Hiệu lực: ${esc(it.ngay_hieu_luc)}</span>` : ""} | |
| </div> | |
| <div class="kb-item-snippet" style="border-left-color: #2e7d32">${esc(it.snippet || it.full_text || "")}</div> | |
| <div class="kb-item-actions"> | |
| <button type="button" class="kb-apply-btn" style="color:#2e7d32;background:rgba(46,125,50,0.08);border-color:rgba(46,125,50,0.3)" onclick="quoteVBPLToComplaint('${esc(it.so_hieu||it.title)}', '${esc(it.section||"")}', '${esc(it.title||"")}')"> | |
| <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg> | |
| <span>Trích dẫn vào phản ánh</span> | |
| </button> | |
| ${it.url ? `<a href="${esc(it.url)}" target="_blank" rel="noopener" class="kb-external-link"> | |
| <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> | |
| <span>Xem trên vbpl.vn</span> | |
| </a>` : ""} | |
| </div> | |
| </div> | |
| `).join(""); | |
| const top = items[0]; | |
| if (top) { | |
| const docEl = document.getElementById("vbplDetailDoc"); | |
| const scopeEl = document.getElementById("vbplDetailScope"); | |
| const appliedEl = document.getElementById("vbplDetailApplied"); | |
| const updatesEl = document.getElementById("vbplDetailUpdates"); | |
| if (docEl) docEl.innerHTML = `<div><strong>${esc(top.title)}</strong></div><div style="margin-top:4px;font-size:12px;color:var(--text-dim,#666)">Số hiệu: ${esc(top.so_hieu || "N/A")} | Cơ quan: ${esc(top.co_quan_ban_hanh || "Quốc hội")}</div>`; | |
| if (scopeEl) scopeEl.innerHTML = `<div>Áp dụng toàn quốc cho các cơ quan, tổ chức, cá nhân liên quan đến lĩnh vực quy định.</div>`; | |
| if (appliedEl) appliedEl.innerHTML = `<div>Áp dụng trực tiếp trong quy trình tiếp nhận, xử lý phản ánh kiến nghị công dân.</div>`; | |
| if (updatesEl) updatesEl.innerHTML = `<div>Trạng thái: <strong>Còn hiệu lực thi hành</strong></div>`; | |
| } | |
| } | |
| } | |
| // Áp dụng thủ tục vào ô phản ánh | |
| function applyTTHCToComplaint(title, docId) { | |
| show("home"); | |
| const qEl = $("#q"); | |
| if (qEl) { | |
| const textToAdd = `Tôi cần giải đáp và hướng dẫn thủ tục: ${title}${docId ? ` (Mã TTHC: ${docId})` : ""}. Cụ thể: `; | |
| qEl.value = textToAdd; | |
| qEl.focus(); | |
| qEl.setSelectionRange(textToAdd.length, textToAdd.length); | |
| } | |
| const slotProc = document.getElementById("slot_procedure_name"); | |
| if (slotProc) slotProc.value = title; | |
| toast(`Đã nạp thủ tục "${title}" vào khung phản ánh!`); | |
| } | |
| // Trích dẫn văn bản vào ô phản ánh | |
| function quoteVBPLToComplaint(soHieu, section, title) { | |
| show("home"); | |
| const qEl = $("#q"); | |
| if (qEl) { | |
| const currentVal = qEl.value.trim(); | |
| const citeText = `Theo quy định tại ${soHieu}${section ? ` (${section})` : ""}...`; | |
| qEl.value = currentVal ? `${currentVal}\\n\\nCăn cứ pháp lý tham khảo: ${citeText}` : `Căn cứ theo quy định tại ${soHieu}${section ? ` (${section})` : ""}: `; | |
| qEl.focus(); | |
| } | |
| toast(`Đã trích dẫn ${soHieu} vào khung phản ánh!`); | |
| } | |
| // Khởi tạo các sự kiện khi DOM sẵn sàng | |
| document.addEventListener("DOMContentLoaded", () => { | |
| // Gắn sự kiện cho TTHC | |
| const tthcBtn = document.getElementById("tthcSearchBtn"); | |
| const tthcInp = document.getElementById("tthcQuery"); | |
| const tthcClr = document.getElementById("tthcClear"); | |
| if (tthcBtn) tthcBtn.addEventListener("click", () => searchKnowledge("tthc")); | |
| if (tthcInp) { | |
| tthcInp.addEventListener("keydown", (e) => { | |
| if (e.key === "Enter") { | |
| e.preventDefault(); | |
| searchKnowledge("tthc"); | |
| } | |
| }); | |
| tthcInp.addEventListener("input", () => { | |
| if (tthcClr) tthcClr.style.display = tthcInp.value ? "block" : "none"; | |
| }); | |
| } | |
| if (tthcClr) { | |
| tthcClr.addEventListener("click", () => { | |
| if (tthcInp) { | |
| tthcInp.value = ""; | |
| tthcClr.style.display = "none"; | |
| tthcInp.focus(); | |
| searchKnowledge("tthc", ""); | |
| } | |
| }); | |
| } | |
| // Gắn sự kiện cho VBPL | |
| const vbplBtn = document.getElementById("vbplSearchBtn"); | |
| const vbplInp = document.getElementById("vbplQuery"); | |
| const vbplClr = document.getElementById("vbplClear"); | |
| if (vbplBtn) vbplBtn.addEventListener("click", () => searchKnowledge("vbpl")); | |
| if (vbplInp) { | |
| vbplInp.addEventListener("keydown", (e) => { | |
| if (e.key === "Enter") { | |
| e.preventDefault(); | |
| searchKnowledge("vbpl"); | |
| } | |
| }); | |
| vbplInp.addEventListener("input", () => { | |
| if (vbplClr) vbplClr.style.display = vbplInp.value ? "block" : "none"; | |
| }); | |
| } | |
| if (vbplClr) { | |
| vbplClr.addEventListener("click", () => { | |
| if (vbplInp) { | |
| vbplInp.value = ""; | |
| vbplClr.style.display = "none"; | |
| vbplInp.focus(); | |
| searchKnowledge("vbpl", ""); | |
| } | |
| }); | |
| } | |
| // Gắn sự kiện cho các chip gợi ý | |
| document.querySelectorAll(".kb-chip[data-kb]").forEach(chip => { | |
| chip.addEventListener("click", () => { | |
| const kbType = chip.dataset.kb; | |
| const q = chip.dataset.q; | |
| show(kbType); | |
| searchKnowledge(kbType, q); | |
| }); | |
| }); | |
| // Tìm kiếm toàn cục từ Header | |
| const globalSearch = document.getElementById("globalSearch"); | |
| if (globalSearch) { | |
| globalSearch.addEventListener("keydown", (e) => { | |
| if (e.key === "Enter") { | |
| e.preventDefault(); | |
| const q = globalSearch.value.trim(); | |
| if (!q) return; | |
| const qLower = q.toLowerCase(); | |
| if (qLower.includes("nghị định") || qLower.includes("luật") || qLower.includes("thông tư") || qLower.includes("điều") || /\\d+\\/\\d+/.test(qLower)) { | |
| show("vbpl"); | |
| searchKnowledge("vbpl", q); | |
| } else { | |
| show("tthc"); | |
| searchKnowledge("tthc", q); | |
| } | |
| } | |
| }); | |
| } | |
| // Khởi tạo hiển thị dữ liệu phổ biến ban đầu | |
| searchKnowledge("tthc", ""); | |
| searchKnowledge("vbpl", ""); | |
| }); | |
| """ | |
| kb_js_code = kb_js_code.replace("___CF_URL___", CF_URL) | |
| kb_js_code = kb_js_code.replace("___TTHC_DATA___", tthc_json_str) | |
| kb_js_code = kb_js_code.replace("___VBPL_DATA___", vbpl_json_str) | |
| full_snippet = "\n" + kb_js_code + "\n</script>\n</body>\n</html>\n" | |
| for path in ["src/inference/static/index.html", "static_space/index.html"]: | |
| p = Path(path) | |
| content = p.read_text(encoding="utf-8") | |
| # Locate first occurrence of KB header | |
| cut_idx = content.find("/* ==========================================================================\n CƠ SỞ TRI THỨC") | |
| if cut_idx == -1: | |
| # Fallback: find </script> before </body> | |
| cut_idx = content.rfind("</script>") | |
| clean_prefix = content[:cut_idx].rstrip() | |
| new_content = clean_prefix + full_snippet | |
| p.write_text(new_content, encoding="utf-8") | |
| print(f"Updated {path} successfully!") | |
| # Validate with node | |
| for path in ["src/inference/static/index.html", "static_space/index.html"]: | |
| content = Path(path).read_text(encoding="utf-8") | |
| scripts = re.findall(r"<script>(.*?)</script>", content, re.DOTALL) | |
| for i, s in enumerate(scripts): | |
| test_file = Path(f"/tmp/validate_{i}.js") | |
| test_file.write_text(s, encoding="utf-8") | |
| res = subprocess.run(["node", "--check", str(test_file)], capture_output=True, text=True) | |
| if res.returncode == 0: | |
| print(f"[{path}] Script tag {i}: VALID JAVASCRIPT! No syntax errors.") | |
| else: | |
| print(f"[{path}] Script tag {i} ERROR:\n{res.stderr}") | |
| exit(1) | |
| print("ALL CHECKS PASSED PERFECTLY!") | |