File size: 17,632 Bytes
46cdd2b
 
 
 
fc4b393
 
46cdd2b
fc4b393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14817f5
fc4b393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad6746
14817f5
5ad6746
 
14817f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad6746
46cdd2b
 
 
fc4b393
 
43e7de8
46cdd2b
43e7de8
5ad6746
14817f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad6746
 
43e7de8
5ad6746
75881bf
5ad6746
051812e
75881bf
26b82ec
75881bf
5ad6746
fc4b393
 
5ad6746
 
 
 
 
46cdd2b
 
 
 
 
14817f5
 
46cdd2b
14817f5
 
 
fc4b393
 
 
 
 
46cdd2b
fc4b393
 
 
14817f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad6746
 
 
14817f5
 
5ad6746
14817f5
 
 
 
 
5ad6746
 
 
 
 
 
 
14817f5
5ad6746
 
 
 
 
 
 
14817f5
5ad6746
 
 
14817f5
5ad6746
14817f5
 
4b479b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14817f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad6746
14817f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad6746
 
14817f5
 
 
5ad6746
 
 
 
14817f5
5ad6746
14817f5
5ad6746
 
 
fc4b393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46cdd2b
fc4b393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43e7de8
46cdd2b
 
fc4b393
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
<!doctype html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Legislation RAG UI</title>
  <style>
    :root {
      --bg: #0b1020;
      --card: #141b2d;
      --muted: #9aa4bf;
      --text: #eef2ff;
      --accent: #5b8cff;
      --accent-2: #27c59a;
      --danger: #ff6b6b;
      --border: #2a3555;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      font-family: Inter, Arial, sans-serif;
      background: radial-gradient(circle at top, #121a33 0%, var(--bg) 45%);
      color: var(--text);
    }
    .container { max-width: 1400px; margin: 0 auto; padding: 16px 16px 20px; min-height: 100vh; }
    h1, h2, h3 { margin: 0 0 10px; }
    .subtitle { color: var(--muted); margin-bottom: 16px; }
    .grid { display: grid; gap: 12px; }
    .grid-2 { grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); }
    .card {
      background: rgba(20, 27, 45, 0.9);
      border: 1px solid var(--border);
      border-radius: 12px;
      padding: 14px;
      margin-top: 12px;
    }
    button {
      border: 1px solid var(--border);
      background: #1f2a44;
      color: var(--text);
      border-radius: 10px;
      padding: 10px 14px;
      cursor: pointer;
      font-weight: 600;
    }
    button.primary { background: var(--accent); border-color: transparent; }
    button.success { background: var(--accent-2); border-color: transparent; }
    button.danger { background: var(--danger); border-color: transparent; }
    button.ghost { background: transparent; }
    input, textarea {
      width: 100%;
      margin-top: 8px;
      margin-bottom: 10px;
      background: #0f1629;
      color: var(--text);
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 10px;
    }
    textarea { min-height: 110px; }
    pre {
      background: #0f1629;
      border: 1px solid var(--border);
      border-radius: 8px;
      padding: 12px;
      white-space: pre-wrap;
      overflow: auto;
      max-height: 360px;
      margin: 0;
    }
    .hidden { display: none; }
    .row { display: flex; gap: 10px; flex-wrap: wrap; }
    .tag { display: inline-block; border: 1px solid var(--border); padding: 4px 8px; border-radius: 999px; color: var(--muted); }
    .chat-thread { display: flex; flex-direction: column; gap: 10px; max-height: 460px; overflow: auto; }
    .msg { border-radius: 12px; padding: 10px 12px; max-width: 90%; line-height: 1.45; }
    .msg-user { align-self: flex-end; background: #29407a; border: 1px solid #3f5fb0; }
    .msg-bot { align-self: flex-start; background: #15213b; border: 1px solid var(--border); }
    .meta { margin-top: 8px; font-size: 12px; color: var(--muted); }

    .user-layout { display: grid; grid-template-columns: minmax(300px, 0.9fr) minmax(520px, 1.4fr) minmax(320px, 1fr); gap: 12px; margin-top: 12px; align-items: start; }
    .doc-list { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; }
    .doc-item { text-align: left; width: 100%; }
    .side-card { height: calc(100vh - 150px); min-height: 700px; display: flex; flex-direction: column; }
    .viewer-card { height: calc(100vh - 150px); min-height: 700px; display: flex; flex-direction: column; }
    .chat-column { display: flex; flex-direction: column; gap: 12px; height: calc(100vh - 150px); min-height: 700px; }
    .chat-column .card:first-child { flex: 0 0 auto; }
    .chat-column .card:last-child { flex: 1; display: flex; flex-direction: column; }
    .chat-column .chat-thread { max-height: none; height: 100%; }
    .doc-status { margin-top: 10px; color: var(--muted); font-size: 14px; }
    .viewer-toolbar { margin-top: 10px; display: flex; gap: 8px; align-items: center; }
    .viewer-toolbar .zoom-label { font-size: 13px; color: var(--muted); min-width: 58px; text-align: center; }
    .viewer-shell { margin-top: 10px; border: 1px solid var(--border); border-radius: 8px; background: #0f1629; min-height: 420px; overflow: hidden; flex: 1; }
    .viewer-shell.paper-mode { background: #bfc5d1; padding: 18px; overflow: auto; }
    .viewer-shell.paper-mode .docx-wrapper { background: transparent !important; padding: 0 !important; }
    .viewer-shell.paper-mode .docx { margin: 0 auto 18px !important; box-shadow: 0 8px 24px rgba(0,0,0,0.24); }
    .docx-zoom-container { height: 100%; overflow: auto; }
    .docx-zoom-content { transform-origin: top center; margin: 0 auto; }
    .doc-frame { width: 100%; height: 100%; min-height: 520px; border: 0; background: #fff; }
    .doc-html-viewer { padding: 20px 24px; line-height: 1.65; background: #f7f8fc; color: #17213d; min-height: 420px; white-space: normal; }
    .doc-html-viewer h4 { margin: 0 0 12px; }
    @media (max-width: 900px) { .user-layout { grid-template-columns: 1fr; } }
  </style>
</head>
<body>
  <div class="container">
    <h1>Legislation GraphRAG</h1>
    <p class="subtitle">Tra cứu văn bản pháp luật và hỏi đáp theo ngữ cảnh tài liệu.</p>

    <div id="userPanel">
      <div class="user-layout">
        <div class="card side-card">
          <div class="row" style="justify-content:space-between; align-items:center;">
            <h3>5 văn bản pháp luật ngẫu nhiên</h3>
            <button onclick="loadRandomDocuments()">Làm mới</button>
          </div>
          <p class="subtitle">Bấm vào tên file để mở trực tiếp trong khung xem ở giữa.</p>
          <div id="randomDocList" class="doc-list"></div>
        </div>

        <div class="card viewer-card">
          <h3>Khung xem văn bản</h3>
          <div id="docStatus" class="doc-status">Chọn một file ở cột trái để mở nội dung.</div>
          <div class="viewer-toolbar">
            <button onclick="zoomOutViewer()">- Thu nhỏ</button>
            <button onclick="zoomInViewer()">+ Phóng to</button>
            <button class="ghost" onclick="resetViewerZoom()">Reset</button>
            <span id="zoomLabel" class="zoom-label">100%</span>
          </div>
          <div id="docViewer" class="viewer-shell"></div>
        </div>

        <div class="chat-column">
          <div class="card">
            <div class="row" style="justify-content:space-between; align-items:center;">
              <h2>Tra cứu pháp luật</h2>
            </div>
            <p class="subtitle">Hãy hỏi các câu hỏi pháp luật trong văn bản hiển thị. Khuyến cáo: Mỗi câu hỏi nên đi kèm tóm gọn tiêu đề của văn bản được hỏi.</p>
            <label for="userQuestion">Câu hỏi</label>
            <textarea id="userQuestion" placeholder="Sở công Thương cần thực hiện các nhiệm vụ gì để bảo đảm cung ứng xăng dầu, khí đốt trên địa bản tỉnh Sơn La năm 2026"></textarea>
              <small class="subtitle" style="display:block; padding-bottom:12px;">
  Vui lòng đợi từ khoảng 30s vì hệ thống dùng CPU-only
</small>
            <button class="primary" onclick="sendUserChat()">Gửi câu hỏi</button>
          </div>

          <div class="card">
            <h3>Hội thoại</h3>
            <div id="userChatThread" class="chat-thread"></div>
          </div>
        </div>
      </div>
    </div>

  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
  <script src="https://unpkg.com/docx-preview@0.3.3/dist/docx-preview.min.js"></script>
  <script>
    let viewerZoom = 1;
    let activeViewerType = 'none';

    async function postJson(url, body) {
      const res = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body || {})
      });
      return await res.json();
    }

    function setViewerMode(mode) {
      const viewerEl = document.getElementById('docViewer');
      viewerEl.classList.remove('paper-mode');
      if (mode === 'docx') {
        viewerEl.classList.add('paper-mode');
      }
    }

    function updateZoomLabel() {
      document.getElementById('zoomLabel').textContent = `${Math.round(viewerZoom * 100)}%`;
    }

    function applyViewerZoom() {
      if (activeViewerType !== 'docx') {
        updateZoomLabel();
        return;
      }
      const zoomRoot = document.getElementById('docxZoomRoot');
      if (!zoomRoot) {
        updateZoomLabel();
        return;
      }
      zoomRoot.style.transform = `scale(${viewerZoom})`;
      zoomRoot.style.width = `${100 / viewerZoom}%`;
      updateZoomLabel();
    }

    function zoomInViewer() {
      viewerZoom = Math.min(2.2, viewerZoom + 0.1);
      applyViewerZoom();
    }

    function zoomOutViewer() {
      viewerZoom = Math.max(0.5, viewerZoom - 0.1);
      applyViewerZoom();
    }

    function resetViewerZoom() {
      viewerZoom = 1;
      applyViewerZoom();
    }


    async function loadRandomDocuments() {
      const listEl = document.getElementById('randomDocList');
      const statusEl = document.getElementById('docStatus');
      const viewerEl = document.getElementById('docViewer');
      listEl.innerHTML = '';
      statusEl.textContent = 'Đang tải danh sách văn bản...';
      viewerEl.innerHTML = '';
      activeViewerType = 'none';
      setViewerMode('default');
      resetViewerZoom();

      try {
        const res = await fetch('/api/documents/random?limit=5');
        const data = await res.json();
        const items = data.items || [];

        if (!items.length) {
          statusEl.textContent = 'Không có file trong data/raw hoặc chưa hỗ trợ định dạng.';
          return;
        }

        items.forEach((item) => {
          const btn = document.createElement('button');
          btn.className = 'doc-item ghost';
          btn.textContent = `${item.filename} (${item.suffix})`;
          btn.onclick = () => loadDocumentPreview(item.filename, item.suffix);
          listEl.appendChild(btn);
        });

        statusEl.textContent = 'Danh sách đã được làm mới. Hãy chọn 1 file để mở trong khung xem.';
      } catch (err) {
        statusEl.textContent = `Lỗi tải danh sách file: ${err}`;
      }

    }

    async function renderDocumentViewer(item, data) {
      const viewerEl = document.getElementById('docViewer');
      const statusEl = document.getElementById('docStatus');
      const suffix = (item.suffix || '').toLowerCase();
      const fileUrl = `/api/documents/file?filename=${encodeURIComponent(item.filename)}`;
      statusEl.textContent = `Đang mở: ${item.filename}`;

      if (suffix === '.pdf') {
        setViewerMode('default');
        activeViewerType = 'pdf';
        viewerEl.innerHTML = `<iframe class="doc-frame" src="${fileUrl}#toolbar=1&navpanes=1"></iframe>`;
        resetViewerZoom();
        return;
      }

      if (suffix === '.docx') {
        await renderDocxWithLibrary(fileUrl, item.filename, data);
        return;
      }

      if (suffix === '.doc') {
        setViewerMode('default');
        activeViewerType = 'fallback';
        viewerEl.innerHTML = `
          <div class="doc-html-viewer">
            <h4>${escapeHtml(item.filename)}</h4>
            <p>File .doc (Word 97-2003) không render chuẩn trực tiếp trên web.</p>
            <p>Hệ thống đã ưu tiên lấy .docx để mở đẹp như file gốc khi có cùng tên.</p>
          </div>
        `;
        return;
      }

      setViewerMode('default');
      activeViewerType = 'fallback';
      const htmlBody = escapeHtml(data.preview || '(Không có nội dung)').replaceAll('\n', '<br />');
      viewerEl.innerHTML = `
        <div class="doc-html-viewer">
          <h4>${escapeHtml(item.filename)}</h4>
          <div>${htmlBody}</div>
        </div>
      `;
    }


    function escapeHtml(value) {
      return String(value || '')
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('\"', '&quot;')
        .replaceAll("'", '&#039;');
    }

    async function renderDocxWithLibrary(fileUrl, filename, data) {
      const viewerEl = document.getElementById('docViewer');
      activeViewerType = 'docx';
      setViewerMode('docx');

      if (!window.JSZip || !window.docx || typeof window.docx.renderAsync !== 'function') {
        setViewerMode('default');
        activeViewerType = 'fallback';
        const htmlBody = escapeHtml(data.preview || '(Không có nội dung)').replaceAll('\n', '<br />');
        viewerEl.innerHTML = `
          <div class="doc-html-viewer">
            <h4>${escapeHtml(filename)}</h4>
            <p>Không tải được thư viện DOCX viewer, hiển thị bản fallback:</p>
            <div>${htmlBody}</div>
          </div>
        `;
        return;
      }

      viewerEl.innerHTML = `
        <div class="docx-zoom-container">
          <div class="docx-zoom-content" id="docxZoomRoot">
            <div class="doc-html-viewer" id="docxRenderRoot"><h4>${escapeHtml(filename)}</h4><div>Đang render file DOCX...</div></div>
          </div>
        </div>
      `;

      const renderRoot = document.getElementById('docxRenderRoot');
      try {
        const fileRes = await fetch(fileUrl);
        if (!fileRes.ok) {
          throw new Error(`HTTP ${fileRes.status}`);
        }

        const fileBuffer = await fileRes.arrayBuffer();
        renderRoot.innerHTML = '';
        await window.docx.renderAsync(fileBuffer, renderRoot, null, {
          className: 'docx',
          inWrapper: false,
          ignoreWidth: false,
          ignoreHeight: false,
          renderHeaders: true,
          renderFooters: true,
          renderFootnotes: true,
          useBase64URL: true,
        });
        applyViewerZoom();
      } catch (error) {
        setViewerMode('default');
        activeViewerType = 'fallback';
        const htmlBody = escapeHtml(data.preview || '(Không có nội dung)').replaceAll('\n', '<br />');
        viewerEl.innerHTML = `
          <div class="doc-html-viewer">
            <h4>${escapeHtml(filename)}</h4>
            <p>Render DOCX lỗi (${escapeHtml(error)}), hiển thị fallback:</p>
            <div>${htmlBody}</div>
          </div>
        `;
      }
    }

    async function renderDocumentViewer(item, data) {
      const viewerEl = document.getElementById('docViewer');
      const statusEl = document.getElementById('docStatus');
      const suffix = (item.suffix || '').toLowerCase();
      const fileUrl = `/api/documents/file?filename=${encodeURIComponent(item.filename)}`;
      statusEl.textContent = `Đang mở: ${item.filename}`;

      if (suffix === '.pdf') {
        setViewerMode('default');
        activeViewerType = 'pdf';
        viewerEl.innerHTML = `<iframe class="doc-frame" src="${fileUrl}#toolbar=1&navpanes=1"></iframe>`;
        resetViewerZoom();
        return;
      }

      if (suffix === '.docx') {
        await renderDocxWithLibrary(fileUrl, item.filename, data);
        return;
      }

      if (suffix === '.doc') {
        setViewerMode('default');
        activeViewerType = 'fallback';
        viewerEl.innerHTML = `
          <div class="doc-html-viewer">
            <h4>${escapeHtml(item.filename)}</h4>
            <p>File .doc (Word 97-2003) không render chuẩn trực tiếp trên web.</p>
            <p>Hệ thống đã ưu tiên lấy .docx để mở đẹp như file gốc khi có cùng tên.</p>
          </div>
        `;
        return;
      }

      setViewerMode('default');
      activeViewerType = 'fallback';
      const htmlBody = escapeHtml(data.preview || '(Không có nội dung)').replaceAll('\n', '<br />');
      viewerEl.innerHTML = `
        <div class="doc-html-viewer">
          <h4>${escapeHtml(item.filename)}</h4>
          <div>${htmlBody}</div>
        </div>
      `;
    }

    async function loadDocumentPreview(filename, suffix = null) {
      const statusEl = document.getElementById('docStatus');
      statusEl.textContent = 'Đang tải nội dung văn bản...';

      try {
        const res = await fetch(`/api/documents/preview?filename=${encodeURIComponent(filename)}`);
        const data = await res.json();
        await renderDocumentViewer({ filename, suffix: suffix || data.suffix || '' }, data);
      } catch (err) {
        statusEl.textContent = `Lỗi tải nội dung file: ${err}`;
      }
    }

    async function sendUserChat() {
      const question = document.getElementById('userQuestion').value.trim();
      if (!question) return;

      const thread = document.getElementById('userChatThread');
      const userNode = document.createElement('div');
      userNode.className = 'msg msg-user';
      userNode.textContent = question;
      thread.appendChild(userNode);

      const botNode = document.createElement('div');
      botNode.className = 'msg msg-bot';
      botNode.textContent = 'Đang xử lý...';
      thread.appendChild(botNode);
      thread.scrollTop = thread.scrollHeight;

      const data = await postJson('/api/chat', {
        question,
        include_debug: false,
      });

      const answer = data.answer || '(không có nội dung trả lời)';
      const meta = document.createElement('div');
      meta.className = 'meta';
      meta.textContent =
        `Nguồn: ${(data.sources || []).length} | Timing: ${JSON.stringify(data.timings_ms || {})}`;

      botNode.textContent = answer;
      botNode.appendChild(meta);
      thread.scrollTop = thread.scrollHeight;
    }

    document.addEventListener('DOMContentLoaded', loadRandomDocuments);
  </script>
</body>
</html>