DANGDOCAO commited on
Commit
e0834ec
·
verified ·
1 Parent(s): b987400

Upload HVU_QA_end_to_end_guide.ipynb

Browse files
Files changed (1) hide show
  1. HVU_QA/HVU_QA_end_to_end_guide.ipynb +646 -0
HVU_QA/HVU_QA_end_to_end_guide.ipynb ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# HVU_QA - Notebook h??ng d?n s? d?ng\n",
8
+ "\n",
9
+ "Notebook n?y ???c t?ch th?nh **2 lu?ng r? r?ng**:\n",
10
+ "- **Ph?n A - Full project**: d?nh cho ng??i t?i to?n b? source code ?? d?ng v? ph?t tri?n ti?p.\n",
11
+ "- **Ph?n B - Ch?y nhanh b?ng tool**: d?nh cho ng??i ch? d?ng `HVU_QA_tool.py` ?? d?ng runtime v? ch?y m? h?nh sinh c?u h?i.\n",
12
+ "\n",
13
+ "Notebook ???c vi?t ?? ch?y t? th? m?c g?c c?a repo `HVU_QA`.\n"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "markdown",
18
+ "metadata": {},
19
+ "source": [
20
+ "## 0. Chuẩn bị helper dùng chung\n",
21
+ "\n",
22
+ "Cell dưới đây sẽ:\n",
23
+ "- tìm thư mục gốc project\n",
24
+ "- chuẩn hóa đường dẫn `venv`\n",
25
+ "- cung cấp hàm chạy lệnh shell từ notebook\n",
26
+ "- cung cấp hàm chờ server phản hồi ổn định\n",
27
+ "- cung cấp thư mục demo cho phần `Quick tool`\n"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "execution_count": null,
34
+ "outputs": [],
35
+ "source": [
36
+ "from __future__ import annotations\n",
37
+ "\n",
38
+ "import json\n",
39
+ "import os\n",
40
+ "import platform\n",
41
+ "import shutil\n",
42
+ "import subprocess\n",
43
+ "import sys\n",
44
+ "import time\n",
45
+ "import urllib.request\n",
46
+ "from pathlib import Path\n",
47
+ "\n",
48
+ "\n",
49
+ "def find_project_root(start: Path) -> Path:\n",
50
+ " current = start.resolve()\n",
51
+ " while True:\n",
52
+ " markers = [\n",
53
+ " current / 'main.py',\n",
54
+ " current / 'requirements.txt',\n",
55
+ " current / 'backend' / 'app.py',\n",
56
+ " current / 'frontend' / 'index.html',\n",
57
+ " current / 'HVU_QA_tool.py',\n",
58
+ " ]\n",
59
+ " if all(marker.exists() for marker in markers):\n",
60
+ " return current\n",
61
+ " if current.parent == current:\n",
62
+ " raise FileNotFoundError('Không tìm thấy thư mục gốc của project HVU_QA từ notebook hiện tại.')\n",
63
+ " current = current.parent\n",
64
+ "\n",
65
+ "\n",
66
+ "PROJECT_ROOT = find_project_root(Path.cwd())\n",
67
+ "os.chdir(PROJECT_ROOT)\n",
68
+ "\n",
69
+ "IS_WINDOWS = platform.system().lower().startswith('win')\n",
70
+ "VENV_DIR = PROJECT_ROOT / 'venv'\n",
71
+ "VENV_PYTHON = VENV_DIR / ('Scripts/python.exe' if IS_WINDOWS else 'bin/python')\n",
72
+ "WEB_LOG_FILE = PROJECT_ROOT / 'hvu_qa_web.log'\n",
73
+ "QUICK_TOOL_DIR = PROJECT_ROOT / '_notebook_quick_tool'\n",
74
+ "QUICK_TOOL_RUNTIME = QUICK_TOOL_DIR / 'HVU_QA_runtime'\n",
75
+ "NOTEBOOK_PYTHON = Path(sys.executable)\n",
76
+ "\n",
77
+ "\n",
78
+ "def print_title(title: str) -> None:\n",
79
+ " print(f'\\n=== {title} ===')\n",
80
+ "\n",
81
+ "\n",
82
+ "def run_command(command: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None, check: bool = True):\n",
83
+ " print_title('Chạy lệnh')\n",
84
+ " print(' '.join(command))\n",
85
+ " result = subprocess.run(\n",
86
+ " command,\n",
87
+ " cwd=str(cwd or PROJECT_ROOT),\n",
88
+ " env=env,\n",
89
+ " text=True,\n",
90
+ " encoding='utf-8',\n",
91
+ " capture_output=True,\n",
92
+ " )\n",
93
+ " if result.stdout:\n",
94
+ " print(result.stdout)\n",
95
+ " if result.stderr:\n",
96
+ " print(result.stderr)\n",
97
+ " if check and result.returncode != 0:\n",
98
+ " raise RuntimeError(f'Lệnh thất bại với mã lỗi {result.returncode}')\n",
99
+ " return result\n",
100
+ "\n",
101
+ "\n",
102
+ "def wait_for_json(url: str, timeout: int = 45):\n",
103
+ " deadline = time.time() + timeout\n",
104
+ " last_error = None\n",
105
+ " while time.time() < deadline:\n",
106
+ " try:\n",
107
+ " with urllib.request.urlopen(url, timeout=3) as response:\n",
108
+ " return json.loads(response.read().decode('utf-8'))\n",
109
+ " except Exception as exc: # noqa: BLE001\n",
110
+ " last_error = exc\n",
111
+ " time.sleep(1)\n",
112
+ " raise RuntimeError(f'Không nhận được phản hồi JSON từ {url} sau {timeout} giây. Lỗi cuối: {last_error}')\n",
113
+ "\n",
114
+ "\n",
115
+ "def read_log_tail(path: Path, lines: int = 40) -> str:\n",
116
+ " if not path.exists():\n",
117
+ " return '(Chưa có log server.)'\n",
118
+ " content = path.read_text(encoding='utf-8', errors='ignore').splitlines()\n",
119
+ " if not content:\n",
120
+ " return '(Log server đang trống.)'\n",
121
+ " return '\\n'.join(content[-lines:])\n",
122
+ "\n",
123
+ "\n",
124
+ "print_title('Thông tin môi trường')\n",
125
+ "print('PROJECT_ROOT =', PROJECT_ROOT)\n",
126
+ "print('Notebook Python =', sys.executable)\n",
127
+ "print('VENV_PYTHON =', VENV_PYTHON)\n",
128
+ "print('IS_WINDOWS =', IS_WINDOWS)\n",
129
+ "print('WEB_LOG_FILE =', WEB_LOG_FILE)\n",
130
+ "print('QUICK_TOOL_DIR =', QUICK_TOOL_DIR)\n"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "markdown",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Phần A - Full project\n",
138
+ "\n",
139
+ "Phần này dành cho trường hợp bạn đã tải **toàn bộ project `HVU_QA`** và muốn dùng hoặc phát triển tiếp.\n"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "markdown",
144
+ "metadata": {},
145
+ "source": [
146
+ "## A1. Kiểm tra cấu trúc project\n",
147
+ "\n",
148
+ "Cell này xác nhận nhanh các file quan trọng đã có trong repo.\n"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "execution_count": null,
155
+ "outputs": [],
156
+ "source": [
157
+ "important_paths = [\n",
158
+ " 'main.py',\n",
159
+ " 'HVU_QA_tool.py',\n",
160
+ " 'requirements.txt',\n",
161
+ " 'backend/app.py',\n",
162
+ " 'backend/__init__.py',\n",
163
+ " 'frontend/index.html',\n",
164
+ " 'frontend/app.js',\n",
165
+ " 'frontend/style.css',\n",
166
+ " 'generate_question.py',\n",
167
+ " 'fine_tune_qg.py',\n",
168
+ "]\n",
169
+ "\n",
170
+ "print_title('Kiểm tra file quan trọng')\n",
171
+ "for item in important_paths:\n",
172
+ " path = PROJECT_ROOT / item\n",
173
+ " print(f'{item:30} ->', 'OK' if path.exists() else 'THIẾU')\n"
174
+ ]
175
+ },
176
+ {
177
+ "cell_type": "markdown",
178
+ "metadata": {},
179
+ "source": [
180
+ "## A2. Tạo môi trường ảo `venv`\n",
181
+ "\n",
182
+ "Cell này sẽ tạo `venv` nếu chưa có.\n"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "execution_count": null,
189
+ "outputs": [],
190
+ "source": [
191
+ "if VENV_PYTHON.exists():\n",
192
+ " print('venv đã tồn tại:', VENV_DIR)\n",
193
+ "else:\n",
194
+ " run_command([sys.executable, '-m', 'venv', str(VENV_DIR)])\n",
195
+ " print('Đã tạo xong venv tại:', VENV_DIR)\n"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "markdown",
200
+ "metadata": {},
201
+ "source": [
202
+ "## A3. Cài dependencies từ `requirements.txt`\n",
203
+ "\n",
204
+ "Cell này dùng cho **full project**. Nếu bạn chỉ dùng launcher một file thì sang **Phần B**.\n"
205
+ ]
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "execution_count": null,
211
+ "outputs": [],
212
+ "source": [
213
+ "run_command([str(VENV_PYTHON), '-m', 'pip', 'install', '--upgrade', 'pip'])\n",
214
+ "run_command([str(VENV_PYTHON), '-m', 'pip', 'install', '-r', str(PROJECT_ROOT / 'requirements.txt')])\n"
215
+ ]
216
+ },
217
+ {
218
+ "cell_type": "markdown",
219
+ "metadata": {},
220
+ "source": [
221
+ "## A4. Tải hoặc đồng bộ model bằng `HVU_QA_tool.py`\n",
222
+ "\n",
223
+ "Notebook gọi tool ở **chế độ full project** để đồng bộ model nếu cần.\n",
224
+ "\n",
225
+ "- `BEST_MODEL_ONLY = False`: tải model gốc + `best-model` theo repo hiện tại.\n",
226
+ "- `BEST_MODEL_ONLY = True`: chỉ tải `best-model`.\n"
227
+ ]
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "execution_count": null,
233
+ "outputs": [],
234
+ "source": [
235
+ "BEST_MODEL_ONLY = False\n",
236
+ "full_project_tool_command = [str(VENV_PYTHON), str(PROJECT_ROOT / 'HVU_QA_tool.py'), '--skip-run']\n",
237
+ "if BEST_MODEL_ONLY:\n",
238
+ " full_project_tool_command.append('--best-model-only')\n",
239
+ "run_command(full_project_tool_command)\n"
240
+ ]
241
+ },
242
+ {
243
+ "cell_type": "markdown",
244
+ "metadata": {},
245
+ "source": [
246
+ "## A5. Kiểm tra model local sau khi tải\n",
247
+ "\n",
248
+ "Nếu ở bước trên dùng `BEST_MODEL_ONLY = True`, notebook sẽ chỉ bắt buộc kiểm tra `best-model`.\n"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "metadata": {},
254
+ "execution_count": null,
255
+ "outputs": [],
256
+ "source": [
257
+ "model_root = PROJECT_ROOT / 't5-viet-qg-finetuned'\n",
258
+ "best_model_only = bool(globals().get('BEST_MODEL_ONLY', False))\n",
259
+ "\n",
260
+ "root_required_files = [\n",
261
+ " model_root / 'config.json',\n",
262
+ " model_root / 'generation_config.json',\n",
263
+ " model_root / 'model.safetensors',\n",
264
+ " model_root / 'tokenizer.json',\n",
265
+ " model_root / 'tokenizer_config.json',\n",
266
+ " model_root / 'special_tokens_map.json',\n",
267
+ " model_root / 'spiece.model',\n",
268
+ "]\n",
269
+ "\n",
270
+ "best_required_files = [\n",
271
+ " model_root / 'best-model' / 'config.json',\n",
272
+ " model_root / 'best-model' / 'generation_config.json',\n",
273
+ " model_root / 'best-model' / 'model.safetensors',\n",
274
+ " model_root / 'best-model' / 'tokenizer.json',\n",
275
+ " model_root / 'best-model' / 'tokenizer_config.json',\n",
276
+ " model_root / 'best-model' / 'special_tokens_map.json',\n",
277
+ " model_root / 'best-model' / 'spiece.model',\n",
278
+ "]\n",
279
+ "\n",
280
+ "print_title('Kiểm tra model local')\n",
281
+ "required_sets = [('best-model', best_required_files)] if best_model_only else [\n",
282
+ " ('model gốc', root_required_files),\n",
283
+ " ('best-model', best_required_files),\n",
284
+ "]\n",
285
+ "\n",
286
+ "for label, files in required_sets:\n",
287
+ " print(f'\\n{label}:')\n",
288
+ " for item in files:\n",
289
+ " print(item.relative_to(PROJECT_ROOT), '->', 'OK' if item.exists() else 'THIẾU')\n"
290
+ ]
291
+ },
292
+ {
293
+ "cell_type": "markdown",
294
+ "metadata": {},
295
+ "source": [
296
+ "## A6. Chạy web app bằng `main.py`\n",
297
+ "\n",
298
+ "Cell này sẽ chạy Flask server ở background, **không tự mở trình duyệt**, và ghi log vào `hvu_qa_web.log`.\n"
299
+ ]
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "metadata": {},
304
+ "execution_count": null,
305
+ "outputs": [],
306
+ "source": [
307
+ "WEB_HOST = '127.0.0.1'\n",
308
+ "WEB_PORT = '5000'\n",
309
+ "base_url = f'http://{WEB_HOST}:{WEB_PORT}'\n",
310
+ "\n",
311
+ "if 'web_process' in globals() and web_process and web_process.poll() is None:\n",
312
+ " print('Web app đang chạy rồi. PID =', web_process.pid)\n",
313
+ " print('URL =', base_url)\n",
314
+ "else:\n",
315
+ " web_env = os.environ.copy()\n",
316
+ " web_env['HVU_HOST'] = WEB_HOST\n",
317
+ " web_env['HVU_PORT'] = WEB_PORT\n",
318
+ " web_env['HVU_OPEN_BROWSER'] = '0'\n",
319
+ "\n",
320
+ " if WEB_LOG_FILE.exists():\n",
321
+ " WEB_LOG_FILE.unlink()\n",
322
+ "\n",
323
+ " with WEB_LOG_FILE.open('w', encoding='utf-8') as log_stream:\n",
324
+ " web_process = subprocess.Popen(\n",
325
+ " [str(VENV_PYTHON), str(PROJECT_ROOT / 'main.py')],\n",
326
+ " cwd=str(PROJECT_ROOT),\n",
327
+ " env=web_env,\n",
328
+ " stdout=log_stream,\n",
329
+ " stderr=subprocess.STDOUT,\n",
330
+ " )\n",
331
+ "\n",
332
+ " try:\n",
333
+ " info_payload = wait_for_json(base_url + '/api/info', timeout=45)\n",
334
+ " except Exception as exc: # noqa: BLE001\n",
335
+ " return_code = web_process.poll()\n",
336
+ " raise RuntimeError(\n",
337
+ " 'Web app không khởi động thành công. '\n",
338
+ " f'returncode={return_code}\\n\\nLog gần nhất:\\n{read_log_tail(WEB_LOG_FILE, lines=80)}'\n",
339
+ " ) from exc\n",
340
+ "\n",
341
+ " print('Đã khởi động web app. PID =', web_process.pid)\n",
342
+ " print('URL =', base_url)\n",
343
+ " print('Model đang chọn =', info_payload.get('selected_model_id'))\n",
344
+ " print('Tên model hiển thị =', info_payload.get('model_name'))\n",
345
+ " print('Log server =', WEB_LOG_FILE)\n"
346
+ ]
347
+ },
348
+ {
349
+ "cell_type": "markdown",
350
+ "metadata": {},
351
+ "source": [
352
+ "## A7. Gọi thử API backend\n",
353
+ "\n",
354
+ "Cell này gọi `GET /api/info`, `POST /api/generate`, và thử `POST /api/model` nếu có nhiều hơn một model khả dụng.\n"
355
+ ]
356
+ },
357
+ {
358
+ "cell_type": "code",
359
+ "metadata": {},
360
+ "execution_count": null,
361
+ "outputs": [],
362
+ "source": [
363
+ "def http_get_json(url: str):\n",
364
+ " with urllib.request.urlopen(url) as response:\n",
365
+ " return json.loads(response.read().decode('utf-8'))\n",
366
+ "\n",
367
+ "\n",
368
+ "def http_post_json(url: str, payload: dict):\n",
369
+ " data = json.dumps(payload, ensure_ascii=False).encode('utf-8')\n",
370
+ " request = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})\n",
371
+ " with urllib.request.urlopen(request) as response:\n",
372
+ " return json.loads(response.read().decode('utf-8'))\n",
373
+ "\n",
374
+ "\n",
375
+ "info_payload = http_get_json(base_url + '/api/info')\n",
376
+ "print_title('GET /api/info')\n",
377
+ "print(json.dumps(info_payload, ensure_ascii=False, indent=2))\n",
378
+ "\n",
379
+ "generate_payload = {\n",
380
+ " 'text': 'Cơ sở giáo dục đại học có nhiệm vụ tổ chức đào tạo, nghiên cứu khoa học và phục vụ cộng đồng.',\n",
381
+ " 'num_questions': 3,\n",
382
+ "}\n",
383
+ "generate_result = http_post_json(base_url + '/api/generate', generate_payload)\n",
384
+ "print_title('POST /api/generate')\n",
385
+ "print(json.dumps(generate_result, ensure_ascii=False, indent=2))\n",
386
+ "\n",
387
+ "available_models = info_payload.get('available_models', [])\n",
388
+ "print_title('Danh sách model khả dụng')\n",
389
+ "print(json.dumps(available_models, ensure_ascii=False, indent=2))\n",
390
+ "\n",
391
+ "if len(available_models) < 2:\n",
392
+ " print('Chỉ có một model khả dụng nên bỏ qua bước chuyển model.')\n",
393
+ "else:\n",
394
+ " current_model_id = info_payload.get('selected_model_id')\n",
395
+ " target_model_id = next(item['id'] for item in available_models if item['id'] != current_model_id)\n",
396
+ " switched_payload = http_post_json(base_url + '/api/model', {'model_id': target_model_id})\n",
397
+ " print_title('POST /api/model')\n",
398
+ " print(json.dumps(switched_payload, ensure_ascii=False, indent=2))\n",
399
+ "\n",
400
+ " restored_payload = http_post_json(base_url + '/api/model', {'model_id': current_model_id})\n",
401
+ " print_title('Khôi phục model ban đầu')\n",
402
+ " print(json.dumps(restored_payload, ensure_ascii=False, indent=2))\n"
403
+ ]
404
+ },
405
+ {
406
+ "cell_type": "markdown",
407
+ "metadata": {},
408
+ "source": [
409
+ "## A8. Chạy `generate_question.py` bằng CLI\n",
410
+ "\n",
411
+ "Cell này minh họa cách chạy CLI trực tiếp mà không cần mở giao diện web.\n"
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "code",
416
+ "metadata": {},
417
+ "execution_count": null,
418
+ "outputs": [],
419
+ "source": [
420
+ "cli_text = 'Cơ sở giáo dục đại học thực hiện hoạt động đào tạo, nghiên cứu khoa học và phục vụ cộng đồng theo quy định của pháp luật.'\n",
421
+ "run_command([\n",
422
+ " str(VENV_PYTHON),\n",
423
+ " str(PROJECT_ROOT / 'generate_question.py'),\n",
424
+ " '--text',\n",
425
+ " cli_text,\n",
426
+ " '--num_questions',\n",
427
+ " '3',\n",
428
+ " '--output_format',\n",
429
+ " 'text',\n",
430
+ "])\n"
431
+ ]
432
+ },
433
+ {
434
+ "cell_type": "markdown",
435
+ "metadata": {},
436
+ "source": [
437
+ "## A9. Xem lệnh fine-tune mẫu\n",
438
+ "\n",
439
+ "Fine-tune là tác vụ nặng, nên notebook chỉ in lệnh mẫu để bạn copy khi cần.\n"
440
+ ]
441
+ },
442
+ {
443
+ "cell_type": "code",
444
+ "metadata": {},
445
+ "execution_count": null,
446
+ "outputs": [],
447
+ "source": [
448
+ "print_title('Fine-tune trên CPU')\n",
449
+ "print(f'{VENV_PYTHON} fine_tune_qg.py --device cpu --output_dir t5-viet-qg-finetuned-cpu')\n",
450
+ "\n",
451
+ "print_title('Fine-tune trên GPU')\n",
452
+ "print(\n",
453
+ " f'{VENV_PYTHON} fine_tune_qg.py --device cuda --fp16 --gradient_checkpointing '\n",
454
+ " '--output_dir t5-viet-qg-finetuned'\n",
455
+ ")\n"
456
+ ]
457
+ },
458
+ {
459
+ "cell_type": "markdown",
460
+ "metadata": {},
461
+ "source": [
462
+ "## A10. Dừng web app\n",
463
+ "\n",
464
+ "Khi không dùng nữa, hãy chạy cell này để dừng server đã bật ở background.\n"
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "code",
469
+ "metadata": {},
470
+ "execution_count": null,
471
+ "outputs": [],
472
+ "source": [
473
+ "if 'web_process' in globals() and web_process and web_process.poll() is None:\n",
474
+ " web_process.terminate()\n",
475
+ " try:\n",
476
+ " web_process.wait(timeout=5)\n",
477
+ " except subprocess.TimeoutExpired:\n",
478
+ " web_process.kill()\n",
479
+ " web_process.wait(timeout=5)\n",
480
+ " print('Đã dừng web app. PID =', web_process.pid)\n",
481
+ "else:\n",
482
+ " print('Không có web app nào đang chạy.')\n"
483
+ ]
484
+ },
485
+ {
486
+ "cell_type": "markdown",
487
+ "metadata": {},
488
+ "source": [
489
+ "# Ph?n B - Ch?y nhanh b?ng tool\n",
490
+ "\n",
491
+ "Ph?n n?y m? ph?ng ??ng tr??ng h?p **ng??i d?ng ch? c? `HVU_QA_tool.py`** trong m?t th? m?c tr?ng.\n",
492
+ "\n",
493
+ "`HVU_QA_tool.py` m?i s?:\n",
494
+ "- t? nh?n bi?t kh?ng c? full project c?nh n?\n",
495
+ "- t? d?ng `HVU_QA_runtime/`\n",
496
+ "- t? t?o virtualenv ri?ng n?u c?n\n",
497
+ "- t? c?i dependencies runtime\n",
498
+ "- t? t?i model t? Hugging Face\n",
499
+ "- t? m? app\n"
500
+ ]
501
+ },
502
+ {
503
+ "cell_type": "markdown",
504
+ "metadata": {},
505
+ "source": [
506
+ "## B1. T?o th? m?c demo ch? ch?a tool\n",
507
+ "\n",
508
+ "Cell n?y sao ch?p `HVU_QA_tool.py` sang m?t th? m?c demo ri?ng.\n"
509
+ ]
510
+ },
511
+ {
512
+ "cell_type": "code",
513
+ "metadata": {},
514
+ "execution_count": null,
515
+ "outputs": [],
516
+ "source": [
517
+ "if QUICK_TOOL_DIR.exists():\n",
518
+ " shutil.rmtree(QUICK_TOOL_DIR)\n",
519
+ "QUICK_TOOL_DIR.mkdir(parents=True, exist_ok=True)\n",
520
+ "shutil.copy2(PROJECT_ROOT / 'HVU_QA_tool.py', QUICK_TOOL_DIR / 'HVU_QA_tool.py')\n",
521
+ "\n",
522
+ "print_title('Thư mục quick tool')\n",
523
+ "for item in QUICK_TOOL_DIR.iterdir():\n",
524
+ " print(item.name)\n"
525
+ ]
526
+ },
527
+ {
528
+ "cell_type": "markdown",
529
+ "metadata": {},
530
+ "source": [
531
+ "## B2. Dựng runtime standalone từ mỗi file tool\n",
532
+ "\n",
533
+ "Cell này chạy `HVU_QA_tool.py` trong thư mục demo ở chế độ `--prepare-runtime-only` để chứng minh rằng tool **không còn phụ thuộc vào full project local**.\n"
534
+ ]
535
+ },
536
+ {
537
+ "cell_type": "code",
538
+ "metadata": {},
539
+ "execution_count": null,
540
+ "outputs": [],
541
+ "source": [
542
+ "run_command([\n",
543
+ " str(NOTEBOOK_PYTHON),\n",
544
+ " str(QUICK_TOOL_DIR / 'HVU_QA_tool.py'),\n",
545
+ " '--prepare-runtime-only',\n",
546
+ "], cwd=QUICK_TOOL_DIR)\n"
547
+ ]
548
+ },
549
+ {
550
+ "cell_type": "markdown",
551
+ "metadata": {},
552
+ "source": [
553
+ "## B3. Kiểm tra runtime được tạo ra\n",
554
+ "\n",
555
+ "Cell này liệt kê các file runtime tối thiểu mà launcher đã tự dựng.\n"
556
+ ]
557
+ },
558
+ {
559
+ "cell_type": "code",
560
+ "metadata": {},
561
+ "execution_count": null,
562
+ "outputs": [],
563
+ "source": [
564
+ "print_title('Các file runtime standalone')\n",
565
+ "for path in sorted(QUICK_TOOL_RUNTIME.rglob('*')):\n",
566
+ " if path.is_file():\n",
567
+ " print(path.relative_to(QUICK_TOOL_DIR).as_posix())\n"
568
+ ]
569
+ },
570
+ {
571
+ "cell_type": "markdown",
572
+ "metadata": {},
573
+ "source": [
574
+ "## B4. L?nh th?t m? ng??i d?ng cu?i s? ch?y\n",
575
+ "\n",
576
+ "Trong th?c t?, ng??i d?ng ch? c?n ??t `HVU_QA_tool.py` v?o m?t th? m?c r?i ch?y l?nh sau.\n"
577
+ ]
578
+ },
579
+ {
580
+ "cell_type": "code",
581
+ "metadata": {},
582
+ "execution_count": null,
583
+ "outputs": [],
584
+ "source": [
585
+ "print_title('L?nh quick tool')\n",
586
+ "print('python HVU_QA_tool.py')\n",
587
+ "print('')\n",
588
+ "print('Launcher s? t? t?o:')\n",
589
+ "print('- .hvu_qa_tool_venv/ n?u m?y ch?a ? trong virtualenv')\n",
590
+ "print('- HVU_QA_runtime/ n?u th? m?c hi?n t?i ch?a c? full project')\n",
591
+ "print('- t5-viet-qg-finetuned/ trong runtime ?? ch?a model')\n"
592
+ ]
593
+ },
594
+ {
595
+ "cell_type": "markdown",
596
+ "metadata": {},
597
+ "source": [
598
+ "## B5. Chạy thật chế độ quick tool\n",
599
+ "\n",
600
+ "Cell dưới đây để **tùy chọn**. Mặc định notebook sẽ không chạy thật vì bước này có thể tải dependencies và model từ Hugging Face.\n",
601
+ "\n",
602
+ "Lưu ý:\n",
603
+ "- repo hiện tại trên Hugging Face đã có cả model gốc và `best-model`\n",
604
+ "- nếu muốn chạy đúng nhánh `best-model`, hãy thêm `--best-model-only` vào lệnh bên dưới\n"
605
+ ]
606
+ },
607
+ {
608
+ "cell_type": "code",
609
+ "metadata": {},
610
+ "execution_count": null,
611
+ "outputs": [],
612
+ "source": [
613
+ "RUN_QUICK_TOOL_NOW = False\n",
614
+ "USE_BEST_MODEL_ONLY = False\n",
615
+ "\n",
616
+ "quick_tool_command = [\n",
617
+ " str(NOTEBOOK_PYTHON),\n",
618
+ " str(QUICK_TOOL_DIR / 'HVU_QA_tool.py'),\n",
619
+ "]\n",
620
+ "if USE_BEST_MODEL_ONLY:\n",
621
+ " quick_tool_command.append('--best-model-only')\n",
622
+ "\n",
623
+ "if RUN_QUICK_TOOL_NOW:\n",
624
+ " run_command(quick_tool_command, cwd=QUICK_TOOL_DIR)\n",
625
+ "else:\n",
626
+ " print('Bỏ qua chạy thật để tránh tải dependency/model ngoài ý muốn.')\n",
627
+ " print('Khi cần, hãy đặt RUN_QUICK_TOOL_NOW = True rồi chạy lại cell này.')\n",
628
+ " print('Lệnh sẽ chạy:')\n",
629
+ " print(' '.join(quick_tool_command))\n"
630
+ ]
631
+ }
632
+ ],
633
+ "metadata": {
634
+ "kernelspec": {
635
+ "display_name": "Python 3",
636
+ "language": "python",
637
+ "name": "python3"
638
+ },
639
+ "language_info": {
640
+ "name": "python",
641
+ "version": "3.11"
642
+ }
643
+ },
644
+ "nbformat": 4,
645
+ "nbformat_minor": 5
646
+ }