{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# HVU_QA - Notebook h??ng d?n s? d?ng\n", "\n", "Notebook n?y ???c t?ch th?nh **2 lu?ng r? r?ng**:\n", "- **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", "- **Ph?n B - Ch?y nhanh b?ng tool**: d?nh cho ng??i ch? d?ng `HVU_QA_tool.py` ho?c `HVU_QA_tool.bat` ?? d?ng runtime v? ch?y m? h?nh sinh c?u h?i.\n", "\n", "Notebook ???c vi?t ?? ch?y t? th? m?c g?c c?a repo `HVU_QA`.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 0. Chu?n b? helper d?ng chung\n", "\n", "Cell d??i ??y s?:\n", "- t?m th? m?c g?c project\n", "- chu?n h?a ???ng d?n `venv`\n", "- cung c?p h?m ch?y l?nh shell t? notebook\n", "- cung c?p h?m ch? server ph?n h?i ?n ??nh\n", "- cung c?p th? m?c demo cho ph?n `Quick tool`\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "from __future__ import annotations\n", "\n", "import json\n", "import os\n", "import platform\n", "import shutil\n", "import subprocess\n", "import sys\n", "import time\n", "import urllib.request\n", "from pathlib import Path\n", "\n", "\n", "def find_project_root(start: Path) -> Path:\n", " current = start.resolve()\n", " while True:\n", " markers = [\n", " current / 'main.py',\n", " current / 'requirements.txt',\n", " current / 'backend' / 'app.py',\n", " current / 'frontend' / 'index.html',\n", " current / 'HVU_QA_tool.py',\n", " ]\n", " if all(marker.exists() for marker in markers):\n", " return current\n", " if current.parent == current:\n", " 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", " current = current.parent\n", "\n", "\n", "PROJECT_ROOT = find_project_root(Path.cwd())\n", "os.chdir(PROJECT_ROOT)\n", "\n", "IS_WINDOWS = platform.system().lower().startswith('win')\n", "VENV_DIR = PROJECT_ROOT / 'venv'\n", "VENV_PYTHON = VENV_DIR / ('Scripts/python.exe' if IS_WINDOWS else 'bin/python')\n", "WEB_LOG_FILE = PROJECT_ROOT / 'hvu_qa_web.log'\n", "QUICK_TOOL_DIR = PROJECT_ROOT / '_notebook_quick_tool'\n", "QUICK_TOOL_RUNTIME = QUICK_TOOL_DIR / 'HVU_QA_runtime'\n", "\n", "\n", "def print_title(title: str) -> None:\n", " print(f'\\n=== {title} ===')\n", "\n", "\n", "def run_command(command: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None, check: bool = True):\n", " print_title('Ch?y l?nh')\n", " print(' '.join(command))\n", " result = subprocess.run(\n", " command,\n", " cwd=str(cwd or PROJECT_ROOT),\n", " env=env,\n", " text=True,\n", " encoding='utf-8',\n", " capture_output=True,\n", " )\n", " if result.stdout:\n", " print(result.stdout)\n", " if result.stderr:\n", " print(result.stderr)\n", " if check and result.returncode != 0:\n", " raise RuntimeError(f'L?nh th?t b?i v?i m? l?i {result.returncode}')\n", " return result\n", "\n", "\n", "def wait_for_json(url: str, timeout: int = 45):\n", " deadline = time.time() + timeout\n", " last_error = None\n", " while time.time() < deadline:\n", " try:\n", " with urllib.request.urlopen(url, timeout=3) as response:\n", " return json.loads(response.read().decode('utf-8'))\n", " except Exception as exc: # noqa: BLE001\n", " last_error = exc\n", " time.sleep(1)\n", " 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", "\n", "\n", "def read_log_tail(path: Path, lines: int = 40) -> str:\n", " if not path.exists():\n", " return '(Ch?a c? log server.)'\n", " content = path.read_text(encoding='utf-8', errors='ignore').splitlines()\n", " if not content:\n", " return '(Log server ?ang tr?ng.)'\n", " return '\\n'.join(content[-lines:])\n", "\n", "\n", "print_title('Th?ng tin m?i tr??ng')\n", "print('PROJECT_ROOT =', PROJECT_ROOT)\n", "print('Notebook Python =', sys.executable)\n", "print('VENV_PYTHON =', VENV_PYTHON)\n", "print('IS_WINDOWS =', IS_WINDOWS)\n", "print('WEB_LOG_FILE =', WEB_LOG_FILE)\n", "print('QUICK_TOOL_DIR =', QUICK_TOOL_DIR)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Ph?n A - Full project\n", "\n", "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" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A1. Ki?m tra c?u tr?c project\n", "\n", "Cell n?y x?c nh?n nhanh c?c file quan tr?ng ?? c? trong repo.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "important_paths = [\n", " 'main.py',\n", " 'HVU_QA_tool.py',\n", " 'requirements.txt',\n", " 'backend/app.py',\n", " 'backend/__init__.py',\n", " 'frontend/index.html',\n", " 'frontend/app.js',\n", " 'frontend/style.css',\n", " 'generate_question.py',\n", " 'fine_tune_qg.py',\n", "]\n", "\n", "print_title('Ki?m tra file quan tr?ng')\n", "for item in important_paths:\n", " path = PROJECT_ROOT / item\n", " print(f'{item:30} ->', 'OK' if path.exists() else 'THI?U')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A2. T?o m?i tr??ng ?o `venv`\n", "\n", "Cell n?y s? t?o `venv` n?u ch?a c?.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "if VENV_PYTHON.exists():\n", " print('venv ?? t?n t?i:', VENV_DIR)\n", "else:\n", " run_command([sys.executable, '-m', 'venv', str(VENV_DIR)])\n", " print('?? t?o xong venv t?i:', VENV_DIR)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A3. C?i dependencies t? `requirements.txt`\n", "\n", "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" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "run_command([str(VENV_PYTHON), '-m', 'pip', 'install', '--upgrade', 'pip'])\n", "run_command([str(VENV_PYTHON), '-m', 'pip', 'install', '-r', str(PROJECT_ROOT / 'requirements.txt')])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A4. T?i ho?c ??ng b? model b?ng `HVU_QA_tool.py`\n", "\n", "Notebook g?i tool ? **ch? ?? full project** ?? ??ng b? model n?u c?n.\n", "\n", "- `BEST_MODEL_ONLY = False`: t?i model g?c theo repo hi?n t?i.\n", "- `BEST_MODEL_ONLY = True`: ch? d?ng khi repo tr?n Hugging Face th?t s? c? th? m?c `best-model`.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "BEST_MODEL_ONLY = False\n", "full_project_tool_command = [str(VENV_PYTHON), str(PROJECT_ROOT / 'HVU_QA_tool.py'), '--skip-run']\n", "if BEST_MODEL_ONLY:\n", " full_project_tool_command.append('--best-model-only')\n", "run_command(full_project_tool_command)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A5. Ki?m tra model local sau khi t?i\n", "\n", "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" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "model_root = PROJECT_ROOT / 't5-viet-qg-finetuned'\n", "best_model_only = bool(globals().get('BEST_MODEL_ONLY', False))\n", "\n", "root_required_files = [\n", " model_root / 'config.json',\n", " model_root / 'generation_config.json',\n", " model_root / 'model.safetensors',\n", " model_root / 'tokenizer_config.json',\n", " model_root / 'special_tokens_map.json',\n", " model_root / 'spiece.model',\n", "]\n", "\n", "best_required_files = [\n", " model_root / 'best-model' / 'config.json',\n", " model_root / 'best-model' / 'generation_config.json',\n", " model_root / 'best-model' / 'model.safetensors',\n", " model_root / 'best-model' / 'tokenizer_config.json',\n", " model_root / 'best-model' / 'special_tokens_map.json',\n", " model_root / 'best-model' / 'spiece.model',\n", "]\n", "\n", "print_title('Ki?m tra model local')\n", "required_sets = [('best-model', best_required_files)] if best_model_only else [\n", " ('model g?c', root_required_files),\n", " ('best-model', best_required_files),\n", "]\n", "\n", "for label, files in required_sets:\n", " print(f'\\n{label}:')\n", " for item in files:\n", " print(item.relative_to(PROJECT_ROOT), '->', 'OK' if item.exists() else 'THI?U')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A6. Ch?y web app b?ng `main.py`\n", "\n", "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" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "WEB_HOST = '127.0.0.1'\n", "WEB_PORT = '5000'\n", "base_url = f'http://{WEB_HOST}:{WEB_PORT}'\n", "\n", "if 'web_process' in globals() and web_process and web_process.poll() is None:\n", " print('Web app ?ang ch?y r?i. PID =', web_process.pid)\n", " print('URL =', base_url)\n", "else:\n", " web_env = os.environ.copy()\n", " web_env['HVU_HOST'] = WEB_HOST\n", " web_env['HVU_PORT'] = WEB_PORT\n", " web_env['HVU_OPEN_BROWSER'] = '0'\n", "\n", " if WEB_LOG_FILE.exists():\n", " WEB_LOG_FILE.unlink()\n", "\n", " with WEB_LOG_FILE.open('w', encoding='utf-8') as log_stream:\n", " web_process = subprocess.Popen(\n", " [str(VENV_PYTHON), str(PROJECT_ROOT / 'main.py')],\n", " cwd=str(PROJECT_ROOT),\n", " env=web_env,\n", " stdout=log_stream,\n", " stderr=subprocess.STDOUT,\n", " )\n", "\n", " try:\n", " info_payload = wait_for_json(base_url + '/api/info', timeout=45)\n", " except Exception as exc: # noqa: BLE001\n", " return_code = web_process.poll()\n", " raise RuntimeError(\n", " 'Web app kh?ng kh?i ??ng th?nh c?ng. '\n", " f'returncode={return_code}\\n\\nLog g?n nh?t:\\n{read_log_tail(WEB_LOG_FILE, lines=80)}'\n", " ) from exc\n", "\n", " print('?? kh?i ??ng web app. PID =', web_process.pid)\n", " print('URL =', base_url)\n", " print('Model ?ang ch?n =', info_payload.get('selected_model_id'))\n", " print('T?n model hi?n th? =', info_payload.get('model_name'))\n", " print('Log server =', WEB_LOG_FILE)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A7. G?i th? API backend\n", "\n", "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" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "def http_get_json(url: str):\n", " with urllib.request.urlopen(url) as response:\n", " return json.loads(response.read().decode('utf-8'))\n", "\n", "\n", "def http_post_json(url: str, payload: dict):\n", " data = json.dumps(payload, ensure_ascii=False).encode('utf-8')\n", " request = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})\n", " with urllib.request.urlopen(request) as response:\n", " return json.loads(response.read().decode('utf-8'))\n", "\n", "\n", "info_payload = http_get_json(base_url + '/api/info')\n", "print_title('GET /api/info')\n", "print(json.dumps(info_payload, ensure_ascii=False, indent=2))\n", "\n", "generate_payload = {\n", " '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", " 'num_questions': 3,\n", "}\n", "generate_result = http_post_json(base_url + '/api/generate', generate_payload)\n", "print_title('POST /api/generate')\n", "print(json.dumps(generate_result, ensure_ascii=False, indent=2))\n", "\n", "available_models = info_payload.get('available_models', [])\n", "print_title('Danh s?ch model kh? d?ng')\n", "print(json.dumps(available_models, ensure_ascii=False, indent=2))\n", "\n", "if len(available_models) < 2:\n", " print('Ch? c? m?t model kh? d?ng n?n b? qua b??c chuy?n model.')\n", "else:\n", " current_model_id = info_payload.get('selected_model_id')\n", " target_model_id = next(item['id'] for item in available_models if item['id'] != current_model_id)\n", " switched_payload = http_post_json(base_url + '/api/model', {'model_id': target_model_id})\n", " print_title('POST /api/model')\n", " print(json.dumps(switched_payload, ensure_ascii=False, indent=2))\n", "\n", " restored_payload = http_post_json(base_url + '/api/model', {'model_id': current_model_id})\n", " print_title('Kh?i ph?c model ban ??u')\n", " print(json.dumps(restored_payload, ensure_ascii=False, indent=2))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A8. Ch?y `generate_question.py` b?ng CLI\n", "\n", "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" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "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", "run_command([\n", " str(VENV_PYTHON),\n", " str(PROJECT_ROOT / 'generate_question.py'),\n", " '--text',\n", " cli_text,\n", " '--num_questions',\n", " '3',\n", " '--output_format',\n", " 'text',\n", "])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A9. Xem l?nh fine-tune m?u\n", "\n", "Fine-tune l? t?c v? n?ng, n?n notebook ch? in l?nh m?u ?? b?n copy khi c?n.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "print_title('Fine-tune tr?n CPU')\n", "print(f'{VENV_PYTHON} fine_tune_qg.py --device cpu --output_dir t5-viet-qg-finetuned-cpu')\n", "\n", "print_title('Fine-tune tr?n GPU')\n", "print(\n", " f'{VENV_PYTHON} fine_tune_qg.py --device cuda --fp16 --gradient_checkpointing '\n", " '--output_dir t5-viet-qg-finetuned'\n", ")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A10. D?ng web app\n", "\n", "Khi kh?ng d?ng n?a, h?y ch?y cell n?y ?? d?ng server ?? b?t ? background.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "if 'web_process' in globals() and web_process and web_process.poll() is None:\n", " web_process.terminate()\n", " try:\n", " web_process.wait(timeout=5)\n", " except subprocess.TimeoutExpired:\n", " web_process.kill()\n", " web_process.wait(timeout=5)\n", " print('?? d?ng web app. PID =', web_process.pid)\n", "else:\n", " print('Kh?ng c? web app n?o ?ang ch?y.')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Ph?n B - Ch?y nhanh b?ng tool\n", "\n", "Ph?n n?y m? ph?ng ??ng tr??ng h?p **ng??i d?ng ch? c? `HVU_QA_tool.py` ho?c `HVU_QA_tool.bat`** trong m?t th? m?c tr?ng.\n", "\n", "`HVU_QA_tool.py` m?i s?:\n", "- t? nh?n bi?t kh?ng c? full project c?nh n?\n", "- t? d?ng `HVU_QA_runtime/`\n", "- t? t?o virtualenv ri?ng n?u c?n\n", "- t? c?i dependencies runtime\n", "- t? t?i model t? Hugging Face\n", "- t? m? app\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B1. T?o th? m?c demo ch? ch?a tool\n", "\n", "Cell n?y sao ch?p `HVU_QA_tool.py` v? `HVU_QA_tool.bat` sang m?t th? m?c demo ri?ng.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "if QUICK_TOOL_DIR.exists():\n", " shutil.rmtree(QUICK_TOOL_DIR)\n", "QUICK_TOOL_DIR.mkdir(parents=True, exist_ok=True)\n", "shutil.copy2(PROJECT_ROOT / 'HVU_QA_tool.py', QUICK_TOOL_DIR / 'HVU_QA_tool.py')\n", "shutil.copy2(PROJECT_ROOT / 'HVU_QA_tool.bat', QUICK_TOOL_DIR / 'HVU_QA_tool.bat')\n", "\n", "print_title('Th? m?c quick tool')\n", "for item in QUICK_TOOL_DIR.iterdir():\n", " print(item.name)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B2. D?ng runtime standalone t? m?i file tool\n", "\n", "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" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "run_command([\n", " str(VENV_PYTHON),\n", " str(QUICK_TOOL_DIR / 'HVU_QA_tool.py'),\n", " '--prepare-runtime-only',\n", "], cwd=QUICK_TOOL_DIR)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B3. Ki?m tra runtime ???c t?o ra\n", "\n", "Cell n?y li?t k? c?c file runtime t?i thi?u m? launcher ?? t? d?ng.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "print_title('C?c file runtime standalone')\n", "for path in sorted(QUICK_TOOL_RUNTIME.rglob('*')):\n", " if path.is_file():\n", " print(path.relative_to(QUICK_TOOL_DIR).as_posix())\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B4. L?nh th?t m? ng??i d?ng cu?i s? ch?y\n", "\n", "Trong th?c t?, ng??i d?ng ch? c?n ??t `HVU_QA_tool.py` ho?c c? c?p `HVU_QA_tool.py` + `HVU_QA_tool.bat` v?o m?t th? m?c r?i ch?y m?t trong c?c l?nh sau.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "print_title('L?nh quick tool')\n", "print('python HVU_QA_tool.py')\n", "print('')\n", "print('Ho?c tr?n Windows: double-click HVU_QA_tool.bat')\n", "print('')\n", "print('Launcher s? t? t?o:')\n", "print('- .hvu_qa_tool_venv/ n?u m?y ch?a ? trong virtualenv')\n", "print('- HVU_QA_runtime/ n?u th? m?c hi?n t?i ch?a c? full project')\n", "print('- t5-viet-qg-finetuned/ trong runtime ?? ch?a model')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B5. Ch?y th?t ch? ?? quick tool\n", "\n", "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", "\n", "L?u ?:\n", "- `--best-model-only` ch? d?ng ???c khi repo tr?n Hugging Face th?t s? c? `best-model`.\n", "- N?u repo hi?n t?i ch? c? model g?c, launcher s? b?o l?i r? r?ng khi b?n ?p `--best-model-only`.\n" ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "RUN_QUICK_TOOL_NOW = False\n", "\n", "quick_tool_command = [\n", " str(VENV_PYTHON),\n", " str(QUICK_TOOL_DIR / 'HVU_QA_tool.py'),\n", "]\n", "\n", "if RUN_QUICK_TOOL_NOW:\n", " run_command(quick_tool_command, cwd=QUICK_TOOL_DIR)\n", "else:\n", " print('B? qua ch?y th?t ?? tr?nh t?i dependency/model ngo?i ? mu?n.')\n", " print('Khi c?n, h?y ??t RUN_QUICK_TOOL_NOW = True r?i ch?y l?i cell n?y.')\n", " print('L?nh s? ch?y:')\n", " print(' '.join(quick_tool_command))\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11" } }, "nbformat": 4, "nbformat_minor": 5 }