ZhangNguyen commited on
Commit
6ae4eae
·
unverified ·
2 Parent(s): 522afb45ad6746

Merge pull request #50 from ZhangNguyen

Browse files

feat(ui): add random legal document preview panel for user mode

src/app/api/documents.py CHANGED
@@ -1,17 +1,19 @@
1
  from __future__ import annotations
2
 
 
3
  from pathlib import Path
4
  from typing import Any, Dict, List
5
- from urllib.parse import quote
6
 
7
- from fastapi import APIRouter
 
8
 
9
  from src.app.settings import settings
10
 
11
  router = APIRouter(prefix="/documents", tags=["documents"])
12
 
13
-
14
- PDF_SUFFIXES = {".pdf"}
 
15
 
16
 
17
  def _display_name(path: Path) -> str:
@@ -19,35 +21,102 @@ def _display_name(path: Path) -> str:
19
  return stem or path.name
20
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  @router.get("")
23
  def list_documents() -> Dict[str, Any]:
 
24
  raw_dir = Path(settings.raw_dir)
25
- if not raw_dir.exists():
26
- return {
27
- "items": [],
28
- "count": 0,
29
- "raw_dir": str(raw_dir),
30
- "exists": False,
31
- }
32
-
33
- items: List[Dict[str, Any]] = []
34
- for fp in sorted(raw_dir.glob("*")):
35
- if not fp.is_file() or fp.suffix.lower() not in PDF_SUFFIXES:
36
- continue
37
- stat = fp.stat()
38
- items.append(
39
  {
40
  "id": fp.stem,
41
  "filename": fp.name,
42
  "title": _display_name(fp),
43
- "size_bytes": stat.st_size,
44
- "view_url": f"/files/raw/{quote(fp.name)}",
45
  }
46
- )
 
 
 
 
 
 
 
 
 
 
 
 
47
 
 
48
  return {
49
- "items": items,
50
- "count": len(items),
51
- "raw_dir": str(raw_dir),
52
- "exists": True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
 
1
  from __future__ import annotations
2
 
3
+ import random
4
  from pathlib import Path
5
  from typing import Any, Dict, List
 
6
 
7
+ from fastapi import APIRouter, HTTPException, Query
8
+ from pypdf import PdfReader
9
 
10
  from src.app.settings import settings
11
 
12
  router = APIRouter(prefix="/documents", tags=["documents"])
13
 
14
+ TEXT_SUFFIXES = {".txt", ".md", ".json", ".csv", ".xml", ".yaml", ".yml"}
15
+ SUPPORTED_SUFFIXES = TEXT_SUFFIXES | {".pdf"}
16
+ MAX_PREVIEW_CHARS = 5000
17
 
18
 
19
  def _display_name(path: Path) -> str:
 
21
  return stem or path.name
22
 
23
 
24
+ def _raw_files() -> List[Path]:
25
+ raw_dir = Path(settings.raw_dir)
26
+ if not raw_dir.exists():
27
+ return []
28
+ return [
29
+ fp
30
+ for fp in raw_dir.glob("*")
31
+ if fp.is_file() and fp.suffix.lower() in SUPPORTED_SUFFIXES
32
+ ]
33
+
34
+
35
+ def _read_preview(path: Path) -> str:
36
+ suffix = path.suffix.lower()
37
+ if suffix in TEXT_SUFFIXES:
38
+ text = path.read_text(encoding="utf-8", errors="ignore")
39
+ return text[:MAX_PREVIEW_CHARS]
40
+
41
+ if suffix == ".pdf":
42
+ reader = PdfReader(str(path))
43
+ chunks: List[str] = []
44
+ total = 0
45
+ for page in reader.pages:
46
+ page_text = (page.extract_text() or "").strip()
47
+ if not page_text:
48
+ continue
49
+ remain = MAX_PREVIEW_CHARS - total
50
+ if remain <= 0:
51
+ break
52
+ snippet = page_text[:remain]
53
+ chunks.append(snippet)
54
+ total += len(snippet)
55
+ return "\n\n".join(chunks)
56
+
57
+ return ""
58
+
59
+
60
  @router.get("")
61
  def list_documents() -> Dict[str, Any]:
62
+ files = sorted(_raw_files())
63
  raw_dir = Path(settings.raw_dir)
64
+ return {
65
+ "items": [
 
 
 
 
 
 
 
 
 
 
 
 
66
  {
67
  "id": fp.stem,
68
  "filename": fp.name,
69
  "title": _display_name(fp),
70
+ "size_bytes": fp.stat().st_size,
71
+ "suffix": fp.suffix.lower(),
72
  }
73
+ for fp in files
74
+ ],
75
+ "count": len(files),
76
+ "raw_dir": str(raw_dir),
77
+ "exists": raw_dir.exists(),
78
+ }
79
+
80
+
81
+ @router.get("/random")
82
+ def random_documents(limit: int = Query(default=5, ge=1, le=20)) -> Dict[str, Any]:
83
+ files = _raw_files()
84
+ if not files:
85
+ return {"items": [], "count": 0}
86
 
87
+ picked = random.sample(files, k=min(limit, len(files)))
88
  return {
89
+ "items": [
90
+ {
91
+ "filename": fp.name,
92
+ "title": _display_name(fp),
93
+ "suffix": fp.suffix.lower(),
94
+ "size_bytes": fp.stat().st_size,
95
+ }
96
+ for fp in picked
97
+ ],
98
+ "count": len(picked),
99
+ }
100
+
101
+
102
+ @router.get("/preview")
103
+ def preview_document(filename: str = Query(..., min_length=1)) -> Dict[str, Any]:
104
+ raw_dir = Path(settings.raw_dir)
105
+ file_path = (raw_dir / filename).resolve()
106
+
107
+ if not raw_dir.exists() or raw_dir.resolve() not in file_path.parents:
108
+ raise HTTPException(status_code=400, detail="Invalid document path")
109
+
110
+ if not file_path.exists() or not file_path.is_file():
111
+ raise HTTPException(status_code=404, detail="File not found")
112
+
113
+ if file_path.suffix.lower() not in SUPPORTED_SUFFIXES:
114
+ raise HTTPException(status_code=400, detail="Unsupported file type")
115
+
116
+ preview_text = _read_preview(file_path).strip()
117
+ return {
118
+ "filename": file_path.name,
119
+ "title": _display_name(file_path),
120
+ "suffix": file_path.suffix.lower(),
121
+ "preview": preview_text or "(Không trích xuất được nội dung xem nhanh)",
122
  }
src/app/api/router.py CHANGED
@@ -4,7 +4,9 @@ from fastapi import APIRouter
4
 
5
  from src.app.api.benchmark import router as benchmark_router
6
  from src.app.api.chat import router as chat_router
 
7
 
8
  api_router = APIRouter()
9
  api_router.include_router(benchmark_router)
10
  api_router.include_router(chat_router)
 
 
4
 
5
  from src.app.api.benchmark import router as benchmark_router
6
  from src.app.api.chat import router as chat_router
7
+ from src.app.api.documents import router as documents_router
8
 
9
  api_router = APIRouter()
10
  api_router.include_router(benchmark_router)
11
  api_router.include_router(chat_router)
12
+ api_router.include_router(documents_router)
src/app/settings.py CHANGED
@@ -42,6 +42,7 @@ class Settings:
42
  qdrant_collection: str = os.getenv("QDRANT_COLLECTION", "legal_chunks")
43
 
44
  normalized_dir: str = os.getenv("NORMALIZED_DIR", "data/normalized")
 
45
  normalized_glob: str = os.getenv("NORMALIZED_GLOB", "*.*")
46
  graph_snapshot_path: str = os.getenv("GRAPH_SNAPSHOT_PATH", "outputs/runtime/runtime_graph_snapshot.json")
47
  bm25_stats_path: str = os.getenv("BM25_STATS_PATH", "outputs/bm25/bm25_stats.json")
 
42
  qdrant_collection: str = os.getenv("QDRANT_COLLECTION", "legal_chunks")
43
 
44
  normalized_dir: str = os.getenv("NORMALIZED_DIR", "data/normalized")
45
+ raw_dir: str = os.getenv("RAW_DIR", "data/raw")
46
  normalized_glob: str = os.getenv("NORMALIZED_GLOB", "*.*")
47
  graph_snapshot_path: str = os.getenv("GRAPH_SNAPSHOT_PATH", "outputs/runtime/runtime_graph_snapshot.json")
48
  bm25_stats_path: str = os.getenv("BM25_STATS_PATH", "outputs/bm25/bm25_stats.json")
src/app/statistic/index.html CHANGED
@@ -77,6 +77,12 @@
77
  .msg-user { align-self: flex-end; background: #29407a; border: 1px solid #3f5fb0; }
78
  .msg-bot { align-self: flex-start; background: #15213b; border: 1px solid var(--border); }
79
  .meta { margin-top: 8px; font-size: 12px; color: var(--muted); }
 
 
 
 
 
 
80
  </style>
81
  </head>
82
  <body>
@@ -94,24 +100,38 @@
94
  </div>
95
 
96
  <div id="userPanel" class="hidden">
97
- <div class="card">
98
- <div class="row" style="justify-content:space-between; align-items:center;">
99
- <h2>User Chat</h2>
100
- <div>
101
- <span class="tag">User mode</span>
102
- <button class="ghost" onclick="backToLanding()">← Quay lại chọn vai trò</button>
 
 
 
 
 
 
 
 
 
103
  </div>
104
- </div>
105
- <p class="subtitle">Chỉ nhập câu hỏi pháp luật. Các tham số retrieval dùng cấu hình server (.env).</p>
106
 
107
- <label for="userQuestion">Câu hỏi</label>
108
- <textarea id="userQuestion" placeholder="Ví dụ: Điều kiện xử phạt theo Điều 77 là gì?"></textarea>
109
- <button class="primary" onclick="sendUserChat()">Gửi câu hỏi</button>
110
- </div>
 
111
 
112
- <div class="card">
113
- <h3>Hội thoại</h3>
114
- <div id="userChatThread" class="chat-thread"></div>
 
 
 
 
 
 
115
  </div>
116
  </div>
117
 
@@ -160,6 +180,7 @@
160
  document.getElementById('landing').classList.add('hidden');
161
  document.getElementById('userPanel').classList.toggle('hidden', role !== 'user');
162
  document.getElementById('adminPanel').classList.toggle('hidden', role !== 'admin');
 
163
  }
164
 
165
  function backToLanding() {
@@ -181,6 +202,50 @@
181
  document.getElementById('adminOutput').textContent = JSON.stringify(data, null, 2);
182
  }
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  async function sendUserChat() {
185
  const question = document.getElementById('userQuestion').value.trim();
186
  if (!question) return;
 
77
  .msg-user { align-self: flex-end; background: #29407a; border: 1px solid #3f5fb0; }
78
  .msg-bot { align-self: flex-start; background: #15213b; border: 1px solid var(--border); }
79
  .meta { margin-top: 8px; font-size: 12px; color: var(--muted); }
80
+
81
+ .user-layout { display: grid; grid-template-columns: minmax(320px, 1fr) minmax(340px, 1fr); gap: 12px; margin-top: 12px; }
82
+ .doc-list { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; }
83
+ .doc-item { text-align: left; width: 100%; }
84
+ .preview-box { min-height: 340px; max-height: 520px; overflow: auto; white-space: pre-wrap; line-height: 1.4; background: #0f1629; border: 1px solid var(--border); border-radius: 8px; padding: 12px; margin-top: 10px; }
85
+ @media (max-width: 900px) { .user-layout { grid-template-columns: 1fr; } }
86
  </style>
87
  </head>
88
  <body>
 
100
  </div>
101
 
102
  <div id="userPanel" class="hidden">
103
+ <div class="user-layout">
104
+ <div>
105
+ <div class="card">
106
+ <div class="row" style="justify-content:space-between; align-items:center;">
107
+ <h2>User Chat</h2>
108
+ <div>
109
+ <span class="tag">User mode</span>
110
+ <button class="ghost" onclick="backToLanding()">← Quay lại chọn vai trò</button>
111
+ </div>
112
+ </div>
113
+ <p class="subtitle">Chỉ nhập câu hỏi pháp luật. Các tham số retrieval dùng cấu hình server (.env).</p>
114
+
115
+ <label for="userQuestion">Câu hỏi</label>
116
+ <textarea id="userQuestion" placeholder="Ví dụ: Điều kiện xử phạt theo Điều 77 là gì?"></textarea>
117
+ <button class="primary" onclick="sendUserChat()">Gửi câu hỏi</button>
118
  </div>
 
 
119
 
120
+ <div class="card">
121
+ <h3>Hội thoại</h3>
122
+ <div id="userChatThread" class="chat-thread"></div>
123
+ </div>
124
+ </div>
125
 
126
+ <div class="card">
127
+ <div class="row" style="justify-content:space-between; align-items:center;">
128
+ <h3>5 văn bản pháp luật ngẫu nhiên</h3>
129
+ <button onclick="loadRandomDocuments()">Làm mới</button>
130
+ </div>
131
+ <p class="subtitle">Bấm vào tên file để xem nhanh nội dung ở khung bên dưới.</p>
132
+ <div id="randomDocList" class="doc-list"></div>
133
+ <div id="docPreview" class="preview-box">Chọn một file để xem nhanh nội dung.</div>
134
+ </div>
135
  </div>
136
  </div>
137
 
 
180
  document.getElementById('landing').classList.add('hidden');
181
  document.getElementById('userPanel').classList.toggle('hidden', role !== 'user');
182
  document.getElementById('adminPanel').classList.toggle('hidden', role !== 'admin');
183
+ if (role === 'user') loadRandomDocuments();
184
  }
185
 
186
  function backToLanding() {
 
202
  document.getElementById('adminOutput').textContent = JSON.stringify(data, null, 2);
203
  }
204
 
205
+
206
+ async function loadRandomDocuments() {
207
+ const listEl = document.getElementById('randomDocList');
208
+ const previewEl = document.getElementById('docPreview');
209
+ listEl.innerHTML = '';
210
+ previewEl.textContent = 'Đang tải danh sách văn bản...';
211
+
212
+ try {
213
+ const res = await fetch('/api/documents/random?limit=5');
214
+ const data = await res.json();
215
+ const items = data.items || [];
216
+
217
+ if (!items.length) {
218
+ previewEl.textContent = 'Không có file trong data/raw hoặc chưa hỗ trợ định dạng.';
219
+ return;
220
+ }
221
+
222
+ items.forEach((item) => {
223
+ const btn = document.createElement('button');
224
+ btn.className = 'doc-item ghost';
225
+ btn.textContent = `${item.filename} (${item.suffix})`;
226
+ btn.onclick = () => loadDocumentPreview(item.filename);
227
+ listEl.appendChild(btn);
228
+ });
229
+
230
+ previewEl.textContent = 'Danh sách đã được làm mới. Hãy chọn 1 file để xem nhanh nội dung.';
231
+ } catch (err) {
232
+ previewEl.textContent = `Lỗi tải danh sách file: ${err}`;
233
+ }
234
+ }
235
+
236
+ async function loadDocumentPreview(filename) {
237
+ const previewEl = document.getElementById('docPreview');
238
+ previewEl.textContent = 'Đang tải nội dung xem nhanh...';
239
+
240
+ try {
241
+ const res = await fetch(`/api/documents/preview?filename=${encodeURIComponent(filename)}`);
242
+ const data = await res.json();
243
+ previewEl.textContent = data.preview || '(Không có nội dung)';
244
+ } catch (err) {
245
+ previewEl.textContent = `Lỗi tải nội dung file: ${err}`;
246
+ }
247
+ }
248
+
249
  async function sendUserChat() {
250
  const question = document.getElementById('userQuestion').value.trim();
251
  if (!question) return;