diff --git a/.env.example b/.env.example
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..c6fd79f6fe226d6cf8dd0d971cafe5c6c06a71ee 100644
--- a/.env.example
+++ b/.env.example
@@ -0,0 +1,17 @@
+# Required for Q&A and learning generation. Never commit a real key.
+GEMINI_API_KEY=
+
+# Optional API protection. Clients then send the X-API-Key header.
+RAG_API_KEY=
+
+# Optional Gradio basic authentication; configure both or neither.
+RAG_GRADIO_USERNAME=
+RAG_GRADIO_PASSWORD=
+
+# Runtime paths and limits.
+RAG_DATA_DIR=data
+RAG_STORAGE_DIR=storage/qdrant
+RAG_EXPORT_DIR=exports
+RAG_MAX_UPLOAD_BYTES=26214400
+RAG_SERVER_NAME=127.0.0.1
+RAG_SERVER_PORT=7860
diff --git a/.gitignore b/.gitignore
index 73ac18ea0f6c264daf29d8a698e6156f661718c4..724bcfba91e9cf2307b81f8a2ed9d472561d29c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,8 +10,41 @@ wheels/
.venv
.env
+.pytest_cache/
+.ruff_cache/
+.coverage
+htmlcov/
+storage/
+exports/
+evaluation-results/
# General
.DS_Store
.AppleDouble
-.LSOverride
\ No newline at end of file
+.LSOverride
+DESIGN.md
+.omo/
+
+# Notebook
+.ipynb_checkpoints/
+
+# Type-checker caches
+.mypy_cache/
+.pyright/
+.basedpyright/
+
+# Logs and temporary files
+*.log
+*.tmp
+*.swp
+
+# Coverage reports
+coverage.xml
+.coverage.*
+
+# Gradio runtime artifacts
+flagged/
+gradio_cached_examples/
+
+data/*.pdf
+data/**/*.pdf
\ No newline at end of file
diff --git a/README.md b/README.md
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..65f97803d4ca4ad2986569d37d727eb2326b8111 100644
--- a/README.md
+++ b/README.md
@@ -0,0 +1,87 @@
+# DocuLearn-RAG
+
+Ứng dụng học tập cục bộ trên PDF, gồm hỏi đáp RAG, tóm tắt, quiz và
+flashcards có trích dẫn nguồn. Giao diện web dùng Gradio; dự án cũng cung cấp
+CLI và REST API.
+
+## Cài đặt
+
+Yêu cầu Python 3.12 và [uv](https://docs.astral.sh/uv/).
+
+```bash
+uv sync --all-groups
+cp .env.example .env
+```
+
+Điền `GEMINI_API_KEY` trong `.env`, hoặc nhập key trực tiếp trong giao diện.
+Không commit file `.env`.
+
+## Chạy ứng dụng
+
+Gradio:
+
+```bash
+uv run python app.py
+```
+
+Mặc định giao diện chạy tại `http://127.0.0.1:7860`.
+
+CLI:
+
+```bash
+uv run doculearn-rag --help
+uv run doculearn-rag ingest
+uv run doculearn-rag ask "Nội dung chính của tài liệu là gì?"
+uv run doculearn-rag summarize --document "example.pdf" --output exports/summary.md
+```
+
+FastAPI:
+
+```bash
+uv run uvicorn src.interfaces.api:app --host 127.0.0.1 --port 8000
+```
+
+OpenAPI docs ở `http://127.0.0.1:8000/docs`. Nếu cấu hình `RAG_API_KEY`, gửi
+header `X-API-Key` cho mọi route trừ `/health`.
+
+## Dữ liệu và cấu hình
+
+- PDF đầu vào: `data/`
+- Qdrant cục bộ: `storage/qdrant/`
+- File Markdown tải từ UI: `exports/`
+- Kích thước upload mặc định: 25 MiB
+
+Các đường dẫn tương đối luôn được resolve theo thư mục gốc dự án, nên CLI/API
+có thể chạy từ working directory khác.
+
+## Kiểm tra
+
+```bash
+uv run pytest -q
+uv run ruff check app.py src tests
+uv run ruff format --check app.py src tests
+uv run basedpyright --level error src
+```
+
+## Đánh giá chunking
+
+File test JSON có dạng:
+
+```json
+[
+ {
+ "question": "Câu hỏi cần đánh giá",
+ "ground_truth": "Câu trả lời tham chiếu"
+ }
+]
+```
+
+Chạy:
+
+```bash
+uv run python -m src.evaluation.run_chunking evaluation_cases.json
+```
+
+Evaluation gọi Gemini và cần `GEMINI_API_KEY`. Dự án ghim Ragas `0.3.9` cùng
+`langchain-community==0.3.31` vì Ragas `0.4.3` hiện import một module VertexAI
+đã bị xóa ở dòng LangChain Community mới.
diff --git a/app.py b/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..16803742a2b08b02fd95deb93c3a066b4ae28c5c
--- /dev/null
+++ b/app.py
@@ -0,0 +1,6 @@
+from src.ui import build_demo, launch_demo
+
+demo = build_demo()
+
+if __name__ == "__main__":
+ launch_demo(demo)
diff --git a/assets/5_Q&A_RAG_Pipeline.png b/assets/5_Q&A_RAG_Pipeline.png
new file mode 100644
index 0000000000000000000000000000000000000000..6f3c9184a56ec91b4639710fa7e3e0d7aa0e3ac7
Binary files /dev/null and b/assets/5_Q&A_RAG_Pipeline.png differ
diff --git a/assets/6_MapReduce_Strategy.png b/assets/6_MapReduce_Strategy.png
new file mode 100644
index 0000000000000000000000000000000000000000..5b15daa3f75fc2b30705b546049c7f650ce25cd9
Binary files /dev/null and b/assets/6_MapReduce_Strategy.png differ
diff --git a/data/[Data]-Benchmark-Rag.csv b/data/[Data]-Benchmark-Rag.csv
new file mode 100644
index 0000000000000000000000000000000000000000..031264b702579b2bbcdb96d2085825d566c4dfd2
--- /dev/null
+++ b/data/[Data]-Benchmark-Rag.csv
@@ -0,0 +1,51 @@
+no.,question,ground truth,
+1,Kỹ thuật Supervised Fine-Tuning (SFT) giúp mô hình học được điều gì ngoài việc biết "trả lời cái gì"?,"SFT còn dạy mô hình ""trả lời như thế nào"", bao gồm việc trả lời đúng vai trò, đúng cấu trúc và kiểu nội dung bài toán yêu cầu.",
+2,Ba vai trò (role) quen thuộc trong định dạng hội thoại của dữ liệu instruction-tuned là gì?,"Dữ liệu được chuyển sang định dạng hội thoại gồm ba vai trò quen thuộc là system, user và assistant.",
+3,Ý tưởng cốt lõi của phương pháp LoRA là gì?,LoRA giữ nguyên trọng số gốc và chỉ học thêm một phần hiệu chỉnh nhỏ có cấu trúc hạng thấp.,
+4,QLoRA khác biệt như thế nào để giúp tiết kiệm bộ nhớ?,QLoRA thiết lập cơ chế lượng tử hóa 4-bit giúp tiết kiệm bộ nhớ.,
+5,Dữ liệu pretraining khác với dữ liệu SFT ở điểm nào?,"Dữ liệu pretraining là các văn bản thô chưa được gắn nhãn, trong khi dữ liệu SFT có cấu trúc đầu vào - đầu ra rõ ràng.",
+6,Hai nguồn dữ liệu tổng quát chính được dùng để pretrain GPT-2 tiếng Việt là gì?,Hai nguồn dữ liệu chính là BKAINewsCorpus và Wikipedia tiếng Việt.,
+7,Mục tiêu huấn luyện của mô hình decoder-only như GPT-2 trong giai đoạn pretraining là gì?,Mục tiêu cốt lõi là dự đoán token tiếp theo dựa trên các token đứng trước đó.,
+8,Tại sao corpus Wikipedia lại được upsampling lặp lại 3 lần so với BKAINews?,"Để điều chỉnh tỉ lệ gradient, giúp mô hình thấy nhiều ví dụ Wikipedia hơn trong mỗi update step và học nhiều hơn từ nguồn dữ liệu có mật độ tri thức cao.",
+9,"Theo quy tắc Chinchilla, kiến trúc GPT-2 small cần khoảng bao nhiêu token để huấn luyện đủ?",Kiến trúc này cần xấp xỉ 2.34 tỷ (2.34B) token.,
+10,Mô hình Generative Pre-trained Transformer (GPT) sử dụng kiến trúc nào?,GPT tiên phong sử dụng kiến trúc decoder-only Transformer và hoàn toàn loại bỏ phần encoder.,
+11,Tập dữ liệu BooksCorpus dùng huấn luyện GPT chứa bao nhiêu mẫu?,Tập dữ liệu BooksCorpus chứa hơn 74 triệu mẫu với kích thước xấp xỉ 4.61GB.,
+12,Fine-tuning trong quá trình phát triển LLM được định nghĩa như thế nào?,"Là giai đoạn huấn luyện tiếp theo sau pre-training, sử dụng tập dữ liệu nhỏ có dán nhãn để cập nhật trọng số, giúp mô hình giải quyết tốt một tác vụ cụ thể.",
+13,Language Model (Mô hình ngôn ngữ) thực chất là gì?,"Là thuật toán ước lượng phân phối xác suất của một chuỗi từ ngữ, thực hiện nhiệm vụ dự đoán từ tiếp theo có khả năng xuất hiện cao nhất.",
+14,Việc mở rộng quy mô (scale) LLM tập trung vào hai yếu tố chính nào?,"Việc mở rộng quy mô này tập trung vào mở rộng về số lượng dữ liệu và mở rộng về số lượng tham số mô hình,.",
+15,Hai nhãn (category) dùng để phân loại tin nhắn rác là gì?,Hai nhãn được sử dụng là Ham (tin nhắn bình thường) và Spam (tin nhắn rác).,
+16,Thư viện FAISS có công dụng gì trong hệ thống vector database?,FAISS hỗ trợ việc tìm kiếm tương đồng và phân cụm các vector với tốc độ và độ chính xác cao.,
+17,Tham số stratify=y trong hàm train_test_split có ý nghĩa gì?,"Tham số này đảm bảo tỉ lệ spam/ham trong hai tập huấn luyện và kiểm thử là tương đương nhau, giúp tránh sai lệch.",
+18,"Khi dùng chỉ mục IndexFlatIP trong FAISS, phép toán nào được dùng để đo độ tương đồng?",Chỉ mục này sử dụng phép toán Tích Vô hướng (Inner Product) để đo độ tương đồng.,
+19,Mô hình ngôn ngữ nào được dùng để tạo sentence embeddings phân loại spam?,Mô hình intfloat/multilingual-e5-base từ Hugging Face được sử dụng để tạo vector đại diện ngữ nghĩa.,
+20,Nhược điểm của SFT khi đối mặt với câu hỏi thực tế là gì?,Không gian câu hỏi của người dùng là vô hạn nên dữ liệu SFT không thể bao phủ hết mọi tình huống.,
+21,Alignment trong LLM là quá trình gì?,"Alignment là quá trình làm cho hành vi của một mô hình ngôn ngữ lớn phù hợp với ý định, giá trị và kỳ vọng của con người.",
+22,Ba tiêu chí cốt lõi (3H) của một LLM đã được aligned là gì?,"Ba tiêu chí đó là helpful (hữu ích), harmless (vô hại) và honest (trung thực).",
+23,Dữ liệu ưu tiên (preference data) cung cấp thông tin gì cho mô hình?,Dữ liệu ưu tiên cho mô hình thấy giữa hai câu trả lời thì câu trả lời A tốt hơn câu trả lời B thay vì chỉ cho xem câu trả lời đúng.,
+24,Reward Model đóng vai trò gì trong huấn luyện RLHF?,"Reward model xuất ra một điểm số vô hướng thể hiện mức độ phù hợp với sở thích của con người, đóng vai trò như một đại diện cho đánh giá của con người,.",
+25,Quá trình RLHF bao gồm 3 giai đoạn nào?,"RLHF bao gồm ba giai đoạn: Supervised Fine-tuning (SFT), huấn luyện reward model và tinh chỉnh bằng Reinforcement Learning (RL),.",
+26,Hiện tượng Sycophancy (xu nịnh) ở LLM là gì?,"Là hiện tượng mô hình không sửa lại thông tin sai của người dùng mà còn đồng tình và bổ sung thêm thông tin sai lệch,.",
+27,Lợi ích của việc yêu cầu con người so sánh cặp câu trả lời thay vì chấm điểm là gì?,Việc con người chọn câu nào tốt hơn đơn giản và dễ hơn rất nhiều so với việc cho điểm chính xác cho từng câu.,
+28,Reward Hacking là hiện tượng như thế nào?,Là hiện tượng mô hình tìm cách tối ưu hóa chỉ số đo lường mà không thực sự cải thiện chất lượng câu trả lời.,
+29,Phương pháp Direct Preference Optimization (DPO) khác gì RLHF?,DPO là phương pháp alignment tối ưu trực tiếp từ dữ liệu ưu tiên mà không cần huấn luyện mô hình phần thưởng riêng biệt.,
+30,LLM Reasoning đòi hỏi mô hình phải làm gì khác so với sinh văn bản thông thường?,Nó đòi hỏi mô hình suy nghĩ từng bước để đưa ra lời giải chính xác và giải thích chi tiết quá trình tư duy.,
+31,Thuật toán học tăng cường nào được dùng để huấn luyện suy luận cho Llama 3.2?,Thuật toán Group Relative Policy Optimization (GRPO) được sử dụng để tăng cường khả năng suy luận.,
+32,"Trong định dạng prompt reasoning, chuỗi suy nghĩ được đặt giữa các thẻ nào?",Chuỗi suy nghĩ được đặt giữa hai thẻ và .,
+33,Đáp án cuối cùng trong bài toán reasoning được đặt ở đâu?,Phần đáp án cuối cùng được đặt giữa hai thẻ và .,
+34,Dataset nào được dùng để cải thiện năng lực giải toán tiếng Việt?,"Bộ dữ liệu MetaMathQA-40K phiên bản tiếng Việt được sử dụng cho mục đích này,.",
+35,Thuật toán GRPO hoạt động dựa trên cơ chế nào?,GRPO giúp tối ưu hóa mô hình bằng cách so sánh kết quả của một nhóm các mẫu thử thay vì sử dụng một mô hình Critic riêng biệt.,
+36,Kỹ thuật Chain-of-Thought (CoT) mang lại lợi ích gì?,CoT yêu cầu mô hình liệt kê các bước lập luận logic từng bước một để giải quyết vấn đề phức tạp thay vì chỉ đưa ra đáp án cuối cùng.,
+37,Hệ thống End-to-end Question Answering bao gồm hai module chính nào?,Một hệ thống tự động bao gồm hai module chính là Document Retriever và Document Reader.,
+38,Nhiệm vụ của thành phần Retriever là gì?,Retriever có nhiệm vụ truy vấn và tìm kiếm các tài liệu có liên quan đến câu hỏi có trong cơ sở dữ liệu.,
+39,Tập dataset chính để huấn luyện đọc hiểu E2E QA trong bài là gì?,Bộ dữ liệu Stanford Question Answering Dataset (SQuAD 2.0) được sử dụng để huấn luyện hệ thống.,
+40,Số lượng bài báo (articles) trong tập Train của SQuAD 2.0 là bao nhiêu?,Tập huấn luyện có chứa thông tin từ tổng cộng 442 bài báo.,
+41,Mô hình pre-trained nào được dùng làm Reader để trích xuất câu trả lời?,"Mô hình DistilBERT, cụ thể là distilbert-base-uncased, được dùng làm Reader.",
+42,"Khi tạo vector đại diện cho câu hỏi bằng BERT, vector của token nào được lấy?","Vector hidden state từ token [CLS] trong kết quả output của mô hình được sử dụng làm đại diện,.",
+43,Metric nào được dùng để đánh giá performance của mô hình QA?,Metric squad_v2 từ thư viện evaluate được dùng để đánh giá mô hình.,
+44,Lợi ích của vector database so với CSDL truyền thống là gì?,"Vector database chuyển đổi dữ liệu thành các biểu diễn Embeddings, cho phép truy xuất dựa trên độ tương đồng ngữ nghĩa thay vì khớp từ khóa.",
+45,Kỹ thuật Quantization trong FAISS có tác dụng gì?,"Kỹ thuật Quantization được sử dụng để nén các vector đa chiều, qua đó giảm thiểu đáng kể dung lượng bộ nhớ khi lưu trữ.",
+46,"Trong đoạn mã FAISS, biến TOP_K có ý nghĩa gì?","Biến TOP_K đại diện cho số lượng kết quả (hàng xóm gần nhất) được trả về trong quá trình tìm kiếm,.",
+47,Lớp Trainer trong HuggingFace giúp ích gì cho quá trình huấn luyện?,"Nó sẽ tự động định nghĩa hàm train, đưa input vào model, tính toán loss và update gradient mà không cần phải tự lập trình thủ công.",
+48,Mục đích của việc thêm tiền tố "passage: " khi tạo embedding là gì?,Thêm tiền tố giúp cải thiện chất lượng embedding cho mô hình E5 khi mã hóa các văn bản.,
+49,Tổng số tham số trainable mới được thêm vào từ LoRA với rank r=16 cho ma trận 2048×2048 là bao nhiêu?,"Tổng số tham số LoRA trainable mới được thêm vào cho mỗi module là 65,536,.",
+50,Kiến trúc Transformer giúp mô hình giải quyết bài toán QA tốt hơn các kiến trúc cũ nhờ cơ chế nào?,"Transformer nắm bắt hiệu quả hơn các phụ thuộc xa (long-range dependencies) thông qua cơ chế self-attention,.",
diff --git a/pyproject.toml b/pyproject.toml
index 46ec14d8a0c04afe018c2a04816b4452677e0745..945b997747b2c12905b54c1a9dfb6657c904e83a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,21 +1,68 @@
[project]
-name = "building-simple-notebooklm"
+name = "doculearn-rag"
version = "0.1.0"
-description = "Add your description here"
+description = "A local PDF-grounded learning assistant with Q&A, summaries, quizzes, and flashcards."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
+ "datasets>=5.0.0",
"fastapi>=0.139.2",
- "langchain>=1.3.14",
- "langchain-community>=0.4.2",
+ "google-genai>=1.0.0",
+ "gradio>=6.20.0",
+ "langchain-community==0.3.31",
"langchain-google-genai>=4.3.1",
- "langchain-huggingface>=1.2.2",
- "langchain-openai>=1.4.0",
"langchain-qdrant>=1.1.0",
- "pip>=26.1.2",
+ "langchain-text-splitters>=1.0.0",
+ "loguru>=0.7.3",
"pydantic>=2.13.4",
+ "pydantic-settings>=2.0.0",
"pypdf>=6.14.2",
+ "python-multipart>=0.0.20",
"qdrant-client>=1.18.0",
- "torch>=2.13.0",
- "transformers>=5.14.1",
+ "ragas==0.3.9",
+ "sentence-transformers>=5.6.0",
+ "typer>=0.21.0",
+ "uvicorn>=0.42.0",
]
+
+[project.scripts]
+doculearn-rag = "src.interfaces.cli:app"
+notebooklm = "src.interfaces.cli:app"
+
+[build-system]
+requires = ["setuptools>=80"]
+build-backend = "setuptools.build_meta"
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["src*"]
+
+[tool.setuptools]
+py-modules = ["app"]
+
+[tool.uv]
+package = true
+
+[dependency-groups]
+dev = [
+ "basedpyright>=1.29.0",
+ "httpx>=0.28.0",
+ "pytest>=9.0.0",
+ "pytest-cov>=7.0.0",
+ "ruff>=0.14.0",
+]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+addopts = ["-ra", "--strict-config", "--strict-markers"]
+
+[tool.ruff]
+target-version = "py312"
+line-length = 100
+
+[tool.ruff.lint]
+select = ["E", "F", "I", "B", "UP"]
+
+[tool.basedpyright]
+include = ["src", "app.py"]
+exclude = ["tests", ".venv", "data", "storage", "exports"]
diff --git a/requirements.txt b/src/__init__.py
similarity index 100%
rename from requirements.txt
rename to src/__init__.py
diff --git a/src/config.py b/src/config.py
index e58bd8124c3da9e94c3b71ac6ada15aaa4290087..df1c2c3802590485215cb3f6e9b9a33b537e1550 100644
--- a/src/config.py
+++ b/src/config.py
@@ -1,75 +1,79 @@
+from __future__ import annotations
+
from functools import lru_cache
from pathlib import Path
from typing import Literal
-from pydantic import Field, model_validator
+from pydantic import Field, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
+_PROJECT_ROOT = Path(__file__).resolve().parents[1]
+
class Settings(BaseSettings):
model_config = SettingsConfigDict(
- env_file=".env",
+ env_file=_PROJECT_ROOT / ".env",
env_prefix="RAG_",
extra="ignore",
)
- # Paths and vector database
data_dir: Path = Path("data")
storage_dir: Path = Path("storage/qdrant")
+ export_dir: Path = Path("exports")
qdrant_collection: str = "rag_chunks"
+ max_upload_bytes: int = Field(default=25 * 1024 * 1024, ge=1024)
- # Chunking and retrieval
- chunk_size: int = Field(default=1000, ge=100)
- chunk_overlap: int = Field(default=150, ge=0)
+ chunk_size: int = Field(default=1500, ge=500)
+ chunk_overlap: int = Field(default=200, ge=0)
top_k: int = Field(default=5, ge=1, le=64)
- # Embedding and LLM
- embedding_model: str = (
- "GreenNode/GreenNode-Embedding-Large-VN-Mixed-V1"
- )
-
- llm_provider: Literal["hf_local", "gemini", "vllm"] = "hf_local"
+ llm_provider: Literal["gemini"] = "gemini"
+ llm_model: str = "gemini-flash-lite-latest"
llm_temperature: float = Field(default=0.1, ge=0.0, le=2.0)
+ llm_max_new_tokens: int = Field(default=10000, ge=1, le=20000)
- # Hugging Face
- hf_device: Literal["mps", "cuda", "cpu"] = "mps"
- hf_max_new_tokens: int = Field(default=2048, ge=1)
-
- # Gemini
- gemini_model: str = "gemini-3.5-flash"
- google_api_key: str | None = Field(
- default=None,
- validation_alias="GOOGLE_API_KEY",
- )
+ embedding_provider: Literal["local"] = "local"
+ embedding_model: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
- # vLLM
- vllm_api_base: str = "http://localhost:8001/v1"
- vllm_api_key: str = "EMPTY"
+ gemini_api_key: str | None = Field(default=None, validation_alias="GEMINI_API_KEY")
+ api_key: str | None = None
+ gradio_username: str | None = None
+ gradio_password: str | None = None
+ server_name: str = "127.0.0.1"
+ server_port: int = Field(default=7860, ge=1, le=65535)
- # Summarization and generation
summarize_batch_size: int = Field(default=10, ge=1)
summarize_retrieval_k: int = Field(default=12, ge=1, le=128)
generation_retrieval_k: int = Field(default=16, ge=1, le=128)
-
- # Learning materials
quiz_default_count: int = Field(default=8, ge=1, le=50)
flashcards_default_count: int = Field(default=15, ge=1, le=100)
- # API
- api_url: str = "http://localhost:8000"
+ @field_validator(
+ "gemini_api_key",
+ "api_key",
+ "gradio_username",
+ "gradio_password",
+ mode="before",
+ )
+ @classmethod
+ def normalize_blank_secrets(cls, value: object) -> object:
+ """Treat blank optional credentials as disabled configuration."""
+ if isinstance(value, str) and not value.strip():
+ return None
+ return value
@model_validator(mode="after")
- def validate_config(self) -> "Settings":
+ def validate_config(self) -> Settings:
if self.chunk_overlap >= self.chunk_size:
+ raise ValueError("chunk_overlap must be smaller than chunk_size.")
+ if bool(self.gradio_username) != bool(self.gradio_password):
raise ValueError(
- "chunk_overlap must be smaller than chunk_size."
- )
-
- if self.llm_provider == "gemini" and not self.google_api_key:
- raise ValueError(
- "GOOGLE_API_KEY is required when "
- "llm_provider='gemini'."
+ "RAG_GRADIO_USERNAME and RAG_GRADIO_PASSWORD must be configured together."
)
+ for field_name in ("data_dir", "storage_dir", "export_dir"):
+ path = getattr(self, field_name)
+ if not path.is_absolute():
+ object.__setattr__(self, field_name, _PROJECT_ROOT / path)
return self
@@ -79,4 +83,4 @@ def get_settings() -> Settings:
return Settings()
-settings = get_settings()
\ No newline at end of file
+settings = get_settings()
diff --git a/src/embeddings.py b/src/embeddings.py
new file mode 100644
index 0000000000000000000000000000000000000000..09d57e4feced0fc1a5ca7bfef463db949995cb07
--- /dev/null
+++ b/src/embeddings.py
@@ -0,0 +1,36 @@
+"""Local embeddings via Sentence-Transformers (no inference provider)."""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import cast
+
+from langchain_core.embeddings import Embeddings
+from sentence_transformers import SentenceTransformer
+
+from src.config import settings
+
+
+@lru_cache(maxsize=1)
+def _model() -> SentenceTransformer:
+ return SentenceTransformer(settings.embedding_model)
+
+
+class LocalSentenceTransformerEmbeddings(Embeddings):
+ def embed_documents(self, texts: list[str]) -> list[list[float]]: # type: ignore[override]
+ vecs = _model().encode(texts, normalize_embeddings=True)
+ tolist = getattr(vecs, "tolist", None)
+ if callable(tolist):
+ return cast(list[list[float]], tolist())
+ return [list(map(float, v)) for v in vecs]
+
+ def embed_query(self, text: str) -> list[float]: # type: ignore[override]
+ vec = _model().encode([text], normalize_embeddings=True)[0]
+ tolist = getattr(vec, "tolist", None)
+ if callable(tolist):
+ return cast(list[float], tolist())
+ return [float(x) for x in vec]
+
+
+def get_embeddings() -> Embeddings:
+ return LocalSentenceTransformerEmbeddings()
diff --git a/src/evaluation/README.md b/src/evaluation/README.md
index fae4433aaef5c1a4dd2c07925cb809351c71c2a5..feecf259270b2bceb4f2d7645d78212bf3de6cea 100644
--- a/src/evaluation/README.md
+++ b/src/evaluation/README.md
@@ -1,3 +1,9 @@
-RAG Evaluation
+# RAG evaluation
-The src/evaluation/ directory contains components for evaluating the quality and performance of the RAG system.
\ No newline at end of file
+`chunking_strategy.py` defines the pre-registered recursive chunking grid.
+`ragas_evaluator.py` converts DocuLearn-RAG answers into a Ragas dataset.
+`run_chunking.py` rebuilds one isolated Qdrant collection per strategy and
+writes mean metric values to `evaluation-results/chunking/`.
+
+Evaluation uses the configured local embedding model and Gemini as judge, so
+it requires `GEMINI_API_KEY` and may incur API usage.
diff --git a/src/evaluation/chunking_strategies.py b/src/evaluation/chunking_strategies.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/src/evaluation/chunking_strategy.py b/src/evaluation/chunking_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..e00c157b0ed2e3bafe40ad2d8a7dda9a10320513
--- /dev/null
+++ b/src/evaluation/chunking_strategy.py
@@ -0,0 +1,61 @@
+"""Reusable chunking strategies for controlled retrieval experiments."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from langchain_core.documents import Document
+from langchain_text_splitters import RecursiveCharacterTextSplitter
+
+from src.indexing import Chunker
+
+DEFAULT_SEPARATORS = ("\n\n", "\n", ". ", " ", "")
+RECURSIVE_CONFIGS = (
+ ("rc_500_50", 500, 50),
+ ("rc_800_100", 800, 100),
+ ("rc_1000_150", 1000, 150),
+ ("rc_1500_200", 1500, 200),
+)
+
+
+@dataclass(frozen=True, slots=True)
+class RecursiveChunker:
+ chunk_size: int = 500
+ chunk_overlap: int = 50
+ separators: tuple[str, ...] = DEFAULT_SEPARATORS
+
+ def __post_init__(self) -> None:
+ if self.chunk_size <= 0:
+ raise ValueError("chunk_size must be positive.")
+ if not 0 <= self.chunk_overlap < self.chunk_size:
+ raise ValueError("chunk_overlap must be non-negative and smaller than chunk_size.")
+
+ def split_documents(self, documents: list[Document]) -> list[Document]:
+ if not documents:
+ return []
+ splitter = RecursiveCharacterTextSplitter(
+ chunk_size=self.chunk_size,
+ chunk_overlap=self.chunk_overlap,
+ separators=list(self.separators),
+ is_separator_regex=False,
+ )
+ return splitter.split_documents(documents)
+
+
+@dataclass(frozen=True, slots=True)
+class ChunkingStrategy:
+ strategy_id: str
+ chunker: Chunker
+ params: dict[str, int]
+
+
+def recursive_strategies() -> list[ChunkingStrategy]:
+ """Build the pre-registered recursive chunking strategy grid."""
+ return [
+ ChunkingStrategy(
+ strategy_id=strategy_id,
+ chunker=RecursiveChunker(chunk_size=chunk_size, chunk_overlap=chunk_overlap),
+ params={"chunk_size": chunk_size, "chunk_overlap": chunk_overlap},
+ )
+ for strategy_id, chunk_size, chunk_overlap in RECURSIVE_CONFIGS
+ ]
diff --git a/src/evaluation/ragas_evaluator.py b/src/evaluation/ragas_evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..8649b3fe53bc1dcfea032085c63d8439b9966518
--- /dev/null
+++ b/src/evaluation/ragas_evaluator.py
@@ -0,0 +1,89 @@
+"""Ragas evaluation adapter for grounded DocuLearn-RAG answers."""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import TypedDict
+
+from datasets import Dataset
+from langchain_google_genai import ChatGoogleGenerativeAI
+
+from src.config import settings
+from src.embeddings import get_embeddings
+from src.rag import answer as default_answer_fn
+from src.schemas import RagAnswer
+
+
+class EvaluationCase(TypedDict):
+ question: str
+ ground_truth: str
+
+
+def _evaluation_dataset(
+ test_cases: list[EvaluationCase],
+ answer_fn: Callable[[str], RagAnswer],
+) -> Dataset:
+ if not test_cases:
+ raise ValueError("test_cases cannot be empty.")
+
+ data: dict[str, list[object]] = {
+ "question": [],
+ "answer": [],
+ "contexts": [],
+ "ground_truth": [],
+ }
+ for index, case in enumerate(test_cases):
+ question = case.get("question", "").strip()
+ ground_truth = case.get("ground_truth", "").strip()
+ if not question or not ground_truth:
+ raise ValueError(
+ "Each test case must contain non-empty 'question' and "
+ f"'ground_truth' values (index {index})."
+ )
+ rag_response = answer_fn(question)
+ data["question"].append(question)
+ data["answer"].append(rag_response.answer)
+ data["contexts"].append([chunk.text for chunk in rag_response.chunks])
+ data["ground_truth"].append(ground_truth)
+ return Dataset.from_dict(data)
+
+
+def run_evaluation(
+ test_cases: list[EvaluationCase],
+ *,
+ answer_fn: Callable[[str], RagAnswer] = default_answer_fn,
+ timeout_s: int = 180,
+ max_retries: int = 3,
+ max_workers: int = 4,
+):
+ """Evaluate grounded answers with Ragas 0.3's stable LangChain adapter."""
+ if not settings.gemini_api_key:
+ raise RuntimeError("GEMINI_API_KEY is required for Ragas evaluation.")
+
+ from ragas import evaluate
+ from ragas.embeddings import LangchainEmbeddingsWrapper
+ from ragas.llms import LangchainLLMWrapper
+ from ragas.metrics import answer_relevancy, context_precision, context_recall, faithfulness
+ from ragas.run_config import RunConfig
+
+ dataset = _evaluation_dataset(test_cases, answer_fn)
+ llm = LangchainLLMWrapper(
+ ChatGoogleGenerativeAI(
+ model=settings.llm_model,
+ google_api_key=settings.gemini_api_key,
+ temperature=settings.llm_temperature,
+ )
+ )
+ embeddings = LangchainEmbeddingsWrapper(get_embeddings())
+ metrics = [faithfulness, answer_relevancy, context_precision, context_recall]
+ return evaluate(
+ dataset=dataset,
+ metrics=metrics,
+ llm=llm,
+ embeddings=embeddings,
+ run_config=RunConfig(
+ timeout=timeout_s,
+ max_retries=max_retries,
+ max_workers=max_workers,
+ ),
+ )
diff --git a/src/evaluation/run_chunking.py b/src/evaluation/run_chunking.py
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..65e96b7fb16f792e2fab62b0e6ff8da2b24010f1 100644
--- a/src/evaluation/run_chunking.py
+++ b/src/evaluation/run_chunking.py
@@ -0,0 +1,94 @@
+"""Run the registered chunking grid against a JSON evaluation set."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any, cast
+
+from src.config import settings
+from src.evaluation.chunking_strategy import recursive_strategies
+from src.evaluation.ragas_evaluator import EvaluationCase, run_evaluation
+from src.indexing import ingest
+from src.rag import answer
+from src.schemas import RagAnswer
+
+
+def _answer_for_collection(collection_name: str):
+ def answer_with_strategy(question: str) -> RagAnswer:
+ return answer(question, collection_name=collection_name)
+
+ return answer_with_strategy
+
+
+def _load_cases(path: Path) -> list[EvaluationCase]:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ if not isinstance(payload, list):
+ raise ValueError("Evaluation file must contain a JSON list.")
+
+ cases: list[EvaluationCase] = []
+ for index, item in enumerate(payload):
+ if not isinstance(item, dict):
+ raise ValueError(f"Evaluation case {index} must be an object.")
+ question = item.get("question")
+ ground_truth = item.get("ground_truth")
+ if not isinstance(question, str) or not isinstance(ground_truth, str):
+ raise ValueError(
+ f"Evaluation case {index} requires string question and ground_truth fields."
+ )
+ cases.append({"question": question, "ground_truth": ground_truth})
+ return cases
+
+
+def run(test_cases_path: Path, output_dir: Path) -> list[dict[str, object]]:
+ cases = _load_cases(test_cases_path)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ reports: list[dict[str, object]] = []
+
+ for strategy in recursive_strategies():
+ collection_name = f"{settings.qdrant_collection}__{strategy.strategy_id}"
+ chunk_count = ingest(
+ recreate=True,
+ collection_name=collection_name,
+ chunker=strategy.chunker,
+ )
+
+ evaluation = run_evaluation(
+ cases,
+ answer_fn=_answer_for_collection(collection_name),
+ )
+ frame = cast(Any, evaluation).to_pandas()
+ numeric = frame.select_dtypes(include="number")
+ metrics = {
+ str(column): float(value) for column, value in numeric.mean(numeric_only=True).items()
+ }
+ report: dict[str, object] = {
+ "strategy_id": strategy.strategy_id,
+ "params": strategy.params,
+ "chunk_count": chunk_count,
+ "metrics": metrics,
+ }
+ (output_dir / f"{strategy.strategy_id}.json").write_text(
+ json.dumps(report, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ reports.append(report)
+
+ return reports
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("test_cases", type=Path)
+ parser.add_argument("--output-dir", type=Path, default=Path("evaluation-results/chunking"))
+ args = parser.parse_args()
+ reports = run(
+ cast(Path, args.test_cases),
+ cast(Path, args.output_dir),
+ )
+ print(json.dumps(reports, ensure_ascii=False, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/evaluation/run_reranking.py b/src/evaluation/run_reranking.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/src/export.py b/src/export.py
index 5d71f05ffc22d99edebc7793acafa90719f97d97..e2428cb104ddd30679f29e6b87d46258613c6ea7 100644
--- a/src/export.py
+++ b/src/export.py
@@ -1 +1,190 @@
-@lru_cache(maxsize=1)
+"""Export learning outputs to JSON or Markdown."""
+
+from __future__ import annotations
+
+import html
+import re
+from pathlib import Path
+from typing import Literal
+
+from pydantic import BaseModel
+
+from src.schemas import Citation, FlashcardSet, QuizSet, RagAnswer, Summary
+
+ExportFormat = Literal["text", "md", "json"]
+_ACTIVE_URI_SCHEME = re.compile(r"\b(?:https?|ftp|javascript|data):", re.IGNORECASE)
+
+
+def _safe(value: str) -> str:
+ """Keep untrusted text readable without retaining active Markdown links."""
+ escaped = html.escape(value, quote=False).replace("[", r"\[").replace("]", r"\]")
+ return _ACTIVE_URI_SCHEME.sub(lambda match: match.group(0)[:-1] + r"\:", escaped)
+
+
+def _safe_inline(value: str) -> str:
+ """Keep untrusted metadata on one inert Markdown line."""
+ return _safe(" ".join(value.splitlines())).replace("`", r"\`")
+
+
+def safe_markdown_code(value: str) -> str:
+ """Render untrusted single-line metadata as an inert Markdown code span."""
+ normalized = html.escape(" ".join(value.splitlines()), quote=False)
+ normalized = _ACTIVE_URI_SCHEME.sub(
+ lambda match: match.group(0)[:-1] + r"\:",
+ normalized,
+ )
+ longest_run = max((len(run) for run in re.findall(r"`+", normalized)), default=0)
+ fence = "`" * (longest_run + 1)
+ padding = " " if normalized.startswith("`") or normalized.endswith("`") else ""
+ return f"{fence}{padding}{normalized}{padding}{fence}"
+
+
+def _citation_line(c: Citation) -> str:
+ parts = [f"[{c.source_marker}] {_safe_inline(c.filename)} p.{c.page}"]
+ if c.section:
+ parts.append(f"section: {_safe_inline(c.section)}")
+ if c.chunk_id:
+ parts.append(f"chunk: {_safe_inline(c.chunk_id)}")
+ return " | ".join(parts)
+
+
+def _details_block(summary: str, content: str) -> str:
+ safe_summary = html.escape(summary, quote=False)
+ safe_content = html.escape(content, quote=False)
+ return (
+ ""
+ f"{safe_summary}"
+ f'
{safe_content}
'
+ ""
+ )
+
+
+def _citation_source_text_block(c: Citation) -> str:
+ if not c.source_text:
+ return ""
+ return "\n " + _details_block("Xem đoạn nguồn", c.source_text)
+
+
+def _marker_details(citations: list[Citation], markers: list[str]) -> list[str]:
+ by_marker = {c.source_marker: c for c in citations}
+ lines: list[str] = []
+ for m in markers:
+ c = by_marker.get(m)
+ if c is None:
+ continue
+ summary = f"[{c.source_marker}] {_safe_inline(c.filename)} p.{c.page}"
+ if c.section:
+ summary += f" | section: {_safe_inline(c.section)}"
+ if c.chunk_id:
+ summary += f" | chunk: {_safe_inline(c.chunk_id)}"
+ if c.source_text:
+ lines.append(f"- {_details_block(summary, c.source_text)}")
+ else:
+ lines.append(f"- {summary}")
+ return lines
+
+
+def _citations_block(citations: list[Citation]) -> str:
+ if not citations:
+ return ""
+ lines = ["## Sources", ""]
+ for c in citations:
+ lines.append(f"- {_citation_line(c)}{_citation_source_text_block(c)}")
+ return "\n".join(lines) + "\n"
+
+
+def _render_with_sources(body_lines: list[str], citations: list[Citation]) -> str:
+ lines = [*body_lines, ""]
+ c = _citations_block(citations)
+ if c:
+ lines.append(c)
+ return "\n".join(lines).rstrip() + "\n"
+
+
+def _to_markdown(model: BaseModel) -> str:
+ if isinstance(model, Summary):
+ title = "# Summary" + (f": {_safe_inline(model.target)}" if model.target else "")
+ lines: list[str] = [title, "", f"_Scope: {model.scope}_", ""]
+ if model.summary:
+ lines.extend([_safe(model.summary.strip()), ""])
+ if model.key_points:
+ lines.extend(["## Key Points", "", *[f"- {_safe(kp)}" for kp in model.key_points], ""])
+ return _render_with_sources(lines, model.citations)
+
+ if isinstance(model, RagAnswer):
+ return _render_with_sources([_safe(model.answer.strip())], model.citations)
+
+ if isinstance(model, QuizSet):
+ title = "# Quiz" + (f": {_safe_inline(model.target)}" if model.target else "")
+ lines = [title, "", f"_Scope: {model.scope} | Items: {len(model.items)}_", ""]
+ for idx, item in enumerate(model.items, start=1):
+ meta_parts: list[str] = []
+ if item.topic:
+ meta_parts.append(f"topic: {_safe_inline(item.topic)}")
+ if item.difficulty:
+ meta_parts.append(f"difficulty: {_safe_inline(item.difficulty)}")
+ meta_suffix = f" _({' | '.join(meta_parts)})_" if meta_parts else ""
+
+ lines.extend([f"## Q{idx}.{meta_suffix}", "", _safe(item.question.strip()), ""])
+ for opt_idx, option in enumerate(item.options):
+ lines.append(f"- {chr(ord('A') + opt_idx)}) {_safe(option)}")
+ lines.append("")
+ lines.append(f"**Answer:** {chr(ord('A') + item.correct_index)}")
+ if item.explanation:
+ lines.append(f"**Explanation:** {_safe(item.explanation.strip())}")
+ if item.source_markers:
+ lines.extend(
+ ["**Sources:**", *_marker_details(model.citations, item.source_markers)]
+ )
+ lines.append("")
+
+ c = _citations_block(model.citations)
+ if c:
+ lines.append(c)
+ return "\n".join(lines).rstrip() + "\n"
+
+ if isinstance(model, FlashcardSet):
+ title = "# Flashcards" + (f": {_safe_inline(model.target)}" if model.target else "")
+ lines = [title, "", f"_Scope: {model.scope} | Cards: {len(model.cards)}_", ""]
+ for idx, card in enumerate(model.cards, start=1):
+ topic = f" — {_safe_inline(card.topic)}" if card.topic else ""
+ lines.extend([f"## Card {idx}{topic}", ""])
+ lines.append(f"**Front:** {_safe(card.front.strip())}")
+ lines.append(f"**Back:** {_safe(card.back.strip())}")
+ if card.hint:
+ lines.append(f"**Hint:** {_safe(card.hint.strip())}")
+ if card.source_markers:
+ lines.extend(
+ ["**Sources:**", *_marker_details(model.citations, card.source_markers)]
+ )
+ lines.append("")
+
+ c = _citations_block(model.citations)
+ if c:
+ lines.append(c)
+ return "\n".join(lines).rstrip() + "\n"
+
+ raise TypeError(f"Unsupported model type: {type(model).__name__}")
+
+
+def export(
+ model: BaseModel, *, fmt: ExportFormat = "text", output: Path | None = None
+) -> str | Path:
+ """Render model to a string, optionally writing it to disk.
+ Args: model, fmt, output (optional).
+ Returns: rendered string if output is None; otherwise the written path.
+ Raises: TypeError for unsupported model type; ValueError for unknown fmt.
+ """
+ if fmt == "json":
+ text = model.model_dump_json(indent=2) + "\n"
+ elif fmt in {"text", "md"}:
+ text = _to_markdown(model)
+ else:
+ raise ValueError(f"Unknown fmt '{fmt}'. Expected 'text' | 'md' | 'json'.")
+
+ if output is None:
+ return text
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(text, encoding="utf-8")
+ return output
diff --git a/src/filters.py b/src/filters.py
index beefce0bf55c0df2517be28961ab54aa873fa08a..b69078f68890b6da43df34330c6cb89231e2df64 100644
--- a/src/filters.py
+++ b/src/filters.py
@@ -1,120 +1,87 @@
-from typing import Any
+"""Shared metadata filtering utilities across the app."""
-from pydantic import BaseModel, field_validator, model_validator
-from qdrant_client import models as qmodels
+from __future__ import annotations
+
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+from qdrant_client.http import models as qmodels
class MetadataFilter(BaseModel):
+ """Filter applied against indexed chunk metadata."""
+
+ model_config = ConfigDict(extra="forbid")
+
filename: str | None = None
filenames: list[str] | None = None
- page: int | None = None
+ page: int | None = Field(default=None, ge=1)
section: str | None = None
document_id: str | None = None
- @field_validator("page")
- @classmethod
- def validate_page(cls, value: int | None) -> int | None:
- if value is not None and value < 1:
- raise ValueError("page must be greater than or equal to 1.")
-
- return value
-
@model_validator(mode="after")
- def normalize(self) -> "MetadataFilter":
- # Chuẩn hóa filename đơn.
- if self.filename is not None:
- self.filename = self.filename.strip() or None
-
- # Chuẩn hóa danh sách filename.
- normalized_names = [
- name.strip()
- for name in (self.filenames or [])
- if isinstance(name, str) and name.strip()
- ]
-
- # Loại bỏ tên trùng nhưng vẫn giữ nguyên thứ tự.
- normalized_names = list(dict.fromkeys(normalized_names))
-
- # Nếu cả filename và filenames cùng được cung cấp,
- # đưa tất cả về filenames.
- if self.filename is not None:
- normalized_names.insert(0, self.filename)
- normalized_names = list(dict.fromkeys(normalized_names))
-
- if not normalized_names:
- self.filename = None
- self.filenames = None
- elif len(normalized_names) == 1:
- self.filename = normalized_names[0]
+ def _normalize(self) -> MetadataFilter:
+ names = [x for x in (self.filenames or []) if isinstance(x, str) and x.strip()]
+ names = [n.strip() for n in names if n.strip()]
+ if not names:
self.filenames = None
+ elif len(names) == 1:
+ self.filename, self.filenames = names[0], None
else:
- self.filename = None
- self.filenames = normalized_names
-
+ # Multi-doc selection: page filter becomes ambiguous, so drop it.
+ self.filename, self.filenames, self.page = None, names, None
+ if self.filename is not None:
+ self.filename = self.filename.strip() or None
if self.section is not None:
self.section = self.section.strip() or None
-
if self.document_id is not None:
self.document_id = self.document_id.strip() or None
-
return self
-def coerce_filter(
- filters: MetadataFilter | dict[str, Any] | None,
-) -> MetadataFilter | None:
+def coerce_filter(filters: MetadataFilter | dict[str, object] | None) -> MetadataFilter | None:
+ """Coerce a dict (or None) into a normalized `MetadataFilter`."""
if filters is None:
return None
-
if isinstance(filters, MetadataFilter):
return filters
-
if isinstance(filters, dict):
return MetadataFilter.model_validate(filters)
+ raise TypeError(f"Unsupported filters type: {type(filters).__name__}")
- raise TypeError(
- "filters must be MetadataFilter, dict, or None."
- )
-
-def filters_to_dict(
- filters: MetadataFilter | dict[str, Any] | None,
-) -> dict[str, Any] | None:
- normalized_filter = coerce_filter(filters)
-
- if normalized_filter is None:
+def filters_to_dict(filters: MetadataFilter | dict[str, object] | None) -> dict[str, object] | None:
+ """Return normalized flat dict suitable for downstream filtering."""
+ f = coerce_filter(filters)
+ if f is None:
return None
-
- result = normalized_filter.model_dump(exclude_none=True)
-
- return result or None
+ return f.model_dump(exclude_none=True) or None
-def filters_to_qdrant(
- filters: MetadataFilter | dict[str, Any] | None,
-) -> qmodels.Filter | None:
- flat_filter = filters_to_dict(filters)
-
- if not flat_filter:
+def filters_to_qdrant(filters: MetadataFilter | dict[str, object] | None) -> qmodels.Filter | None:
+ """Build a Qdrant filter from normalized metadata filters."""
+ flat = filters_to_dict(filters)
+ if not flat:
return None
- conditions: list[qmodels.FieldCondition] = []
+ conditions: list[qmodels.Condition] = []
+ for field, value in flat.items():
+ if value is None:
+ continue
- for field_name, value in flat_filter.items():
- if field_name == "filenames":
- conditions.append(
- qmodels.FieldCondition(
- key="metadata.filename",
- match=qmodels.MatchAny(any=value),
+ if field == "filenames" and isinstance(value, list):
+ names = [x for x in value if isinstance(x, str) and x]
+ if names:
+ conditions.append(
+ qmodels.FieldCondition(
+ key="metadata.filename", match=qmodels.MatchAny(any=names)
+ )
)
- )
continue
- conditions.append(
- qmodels.FieldCondition(
- key=f"metadata.{field_name}",
- match=qmodels.MatchValue(value=value),
+ if isinstance(value, (str, int)):
+ conditions.append(
+ qmodels.FieldCondition(
+ key=f"metadata.{field}", match=qmodels.MatchValue(value=value)
+ )
)
- )
- return qmodels.Filter(must=conditions)
\ No newline at end of file
+ return qmodels.Filter(must=conditions) if conditions else None
diff --git a/src/indexing.py b/src/indexing.py
index 111ce5c99b8dab5aafd6801f5e21306eea859120..0fa15aea88e0a01850c1f0c21f70e6e2ace25092 100644
--- a/src/indexing.py
+++ b/src/indexing.py
@@ -1,303 +1,244 @@
+"""Load PDFs, split into chunks with metadata, and index into Qdrant."""
+
+from __future__ import annotations
+
import hashlib
+import os
+import tempfile
import uuid
from collections import defaultdict
-from collections.abc import Iterable, Sequence
from pathlib import Path
+from typing import Protocol
from langchain_community.document_loaders import PyPDFLoader
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
+from loguru import logger
-from config import settings
-from schemas import ChunkMetadata
-from store import ensure_collection, get_vector_store
-
+from src.config import settings
+from src.schemas import ChunkMetadata
+from src.store import delete_old_document_versions, ensure_collection, get_vector_store
-def _document_id(path: Path) -> str:
- hasher = hashlib.sha256()
- with path.open("rb") as file:
- for block in iter(lambda: file.read(1024 * 1024), b""):
- hasher.update(block)
+_PDF_SIGNATURE = b"%PDF-"
- return hasher.hexdigest()[:16]
+class Chunker(Protocol):
+ def split_documents(self, documents: list[Document]) -> list[Document]:
+ """Split page-level documents into chunk-level documents."""
+ ...
-def _chunk_id(
- document_id: str,
- page: int,
- index: int,
-) -> str:
- return f"{document_id}:{page}:{index}"
+def _splitter(
+ chunk_size: int | None = None, chunk_overlap: int | None = None
+) -> RecursiveCharacterTextSplitter:
+ size = settings.chunk_size if chunk_size is None else chunk_size
+ overlap = settings.chunk_overlap if chunk_overlap is None else chunk_overlap
-def discover_pdfs() -> list[Path]:
- """
- Tìm tất cả PDF trong thư mục dữ liệu.
- """
- settings.data_dir.mkdir(
- parents=True,
- exist_ok=True,
- )
-
- return sorted(
- path
- for path in settings.data_dir.rglob("*.pdf")
- if path.is_file()
+ return RecursiveCharacterTextSplitter(
+ chunk_size=size,
+ chunk_overlap=overlap,
+ separators=["\n\n", "\n", ". ", " ", ""],
+ keep_separator=False,
)
-def _load_pdf(path: Path) -> list[Document]:
- path = path.expanduser()
-
- if not path.exists():
- raise FileNotFoundError(
- f"PDF file not found: {path}"
- )
+def _document_id(path: Path, filename: str | None = None) -> str:
+ """Build a stable identity from the logical filename and complete file content."""
+ digest = hashlib.sha256()
+ digest.update((filename or path.name).encode("utf-8"))
+ digest.update(b"\0")
+ with path.open("rb") as file_obj:
+ for block in iter(lambda: file_obj.read(1024 * 1024), b""):
+ digest.update(block)
+ return digest.hexdigest()[:24]
- if not path.is_file():
- raise ValueError(
- f"Path is not a file: {path}"
- )
- if path.suffix.lower() != ".pdf":
- raise ValueError(
- f"Expected a PDF file, received: {path.suffix}"
- )
+def _chunk_id(doc_id: str, page: int, index: int) -> str:
+ return f"{doc_id}:{page}:{index}"
- pages = PyPDFLoader(str(path)).load()
- document_id = _document_id(path)
-
- for document in pages:
- original_page = document.metadata.get("page", 0)
-
- try:
- page_number = int(original_page) + 1
- except (TypeError, ValueError) as error:
- raise ValueError(
- f"Invalid page metadata in PDF {path}: "
- f"{original_page!r}"
- ) from error
-
- document.metadata.update(
- {
- "document_id": document_id,
- "filename": path.name,
- "source": str(path.resolve()),
- "page": page_number,
- "section": document.metadata.get("section"),
- }
- )
+def _load_pdf(
+ path: Path,
+ *,
+ filename: str | None = None,
+ source: str | None = None,
+) -> list[Document]:
+ loader = PyPDFLoader(str(path))
+ pages = loader.load()
+ logical_filename = filename or path.name
+ doc_id = _document_id(path, logical_filename)
+ for doc in pages:
+ page_number = int(doc.metadata.get("page", 0)) + 1
+ doc.metadata = {
+ "document_id": doc_id,
+ "filename": logical_filename,
+ "source": source or logical_filename,
+ "page": page_number,
+ "section": doc.metadata.get("section"),
+ }
return pages
-def _splitter(
- chunk_size: int | None = None,
- chunk_overlap: int | None = None,
-) -> RecursiveCharacterTextSplitter:
- resolved_chunk_size = (
- settings.chunk_size
- if chunk_size is None
- else chunk_size
- )
-
- resolved_chunk_overlap = (
- settings.chunk_overlap
- if chunk_overlap is None
- else chunk_overlap
- )
-
- if resolved_chunk_size <= 0:
- raise ValueError(
- "chunk_size must be greater than 0."
- )
-
- if resolved_chunk_overlap < 0:
- raise ValueError(
- "chunk_overlap cannot be negative."
- )
-
- if resolved_chunk_overlap >= resolved_chunk_size:
- raise ValueError(
- "chunk_overlap must be smaller than chunk_size."
- )
-
- return RecursiveCharacterTextSplitter(
- chunk_size=resolved_chunk_size,
- chunk_overlap=resolved_chunk_overlap,
- separators=[
- "\n\n",
- "\n",
- ". ",
- " ",
- "",
- ],
- keep_separator=False,
- )
+def discover_pdfs(data_dir: Path | None = None) -> list[Path]:
+ directory = data_dir or settings.data_dir
+ if not directory.exists():
+ return []
+ return sorted(p for p in directory.iterdir() if p.is_file() and p.suffix.lower() == ".pdf")
def build_chunks(
- pdf_paths: Iterable[Path | str],
+ pdf_paths: list[Path],
chunk_size: int | None = None,
chunk_overlap: int | None = None,
- chunker: RecursiveCharacterTextSplitter | None = None,
+ chunker: Chunker | None = None,
+ filename_override: str | None = None,
+ source_override: str | None = None,
) -> list[Document]:
- if chunker is not None and (
- chunk_size is not None
- or chunk_overlap is not None
- ):
- raise ValueError(
- "Pass either chunker or chunk_size/chunk_overlap, "
- "not both."
- )
-
- page_documents: list[Document] = []
-
+ page_docs: list[Document] = []
for path in pdf_paths:
- page_documents.extend(
- _load_pdf(Path(path))
+ logger.info("Loading PDF: {}", path.name)
+ page_docs.extend(
+ _load_pdf(
+ path,
+ filename=filename_override,
+ source=source_override,
+ )
)
- if not page_documents:
- return []
-
- splitter = chunker or _splitter(
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- )
-
- chunks = splitter.split_documents(page_documents)
-
- # Mỗi tài liệu và mỗi trang có bộ đếm chunk riêng.
- per_page_counter: defaultdict[
- tuple[str, int],
- int,
- ] = defaultdict(int)
+ if chunker is None:
+ chunks = _splitter(chunk_size, chunk_overlap).split_documents(page_docs)
+ else:
+ chunks = chunker.split_documents(page_docs)
+ per_doc_counter: dict[str, int] = defaultdict(int)
for chunk in chunks:
- document_id = str(
- chunk.metadata["document_id"]
- )
- page = int(chunk.metadata["page"])
- counter_key = (document_id, page)
-
- index = per_page_counter[counter_key]
- per_page_counter[counter_key] += 1
-
- metadata = ChunkMetadata(
- document_id=document_id,
- filename=str(chunk.metadata["filename"]),
- source=str(chunk.metadata["source"]),
- page=page,
- chunk_id=_chunk_id(
- document_id=document_id,
- page=page,
- index=index,
- ),
+ doc_id = chunk.metadata["document_id"]
+ idx = per_doc_counter[doc_id]
+ per_doc_counter[doc_id] += 1
+ meta = ChunkMetadata(
+ document_id=doc_id,
+ filename=chunk.metadata["filename"],
+ source=chunk.metadata["source"],
+ page=chunk.metadata["page"],
+ chunk_id=_chunk_id(doc_id, chunk.metadata["page"], idx),
section=chunk.metadata.get("section"),
)
-
- chunk.metadata = metadata.model_dump(
- exclude_none=True
- )
-
+ chunk.metadata = meta.model_dump()
return chunks
-def index_chunks(
- chunks: Sequence[Document],
- collection_name: str | None = None,
-) -> int:
+def index_chunks(chunks: list[Document], collection_name: str | None = None) -> int:
+ """Compute deterministic UUIDs and add chunks to the vector store.
+
+ Re-ingesting the same content upserts instead of creating duplicates.
+ """
if not chunks:
return 0
+ ids = [str(uuid.uuid5(uuid.NAMESPACE_DNS, c.metadata["chunk_id"])) for c in chunks]
+ get_vector_store(collection_name=collection_name).add_documents(chunks, ids=ids)
+ return len(chunks)
- ids = [
- str(
- uuid.uuid5(
- uuid.NAMESPACE_URL,
- str(chunk.metadata["chunk_id"]),
- )
- )
- for chunk in chunks
- ]
-
- vector_store = get_vector_store(
- collection_name=collection_name
- )
-
- vector_store.add_documents(
- documents=list(chunks),
- ids=ids,
- )
- return len(chunks)
+def _remove_stale_versions(
+ chunks: list[Document],
+ collection_name: str | None = None,
+) -> None:
+ """Remove older vector versions after all replacement chunks are available."""
+ current_versions = {
+ (str(chunk.metadata["filename"]), str(chunk.metadata["document_id"])) for chunk in chunks
+ }
+ for filename, document_id in current_versions:
+ delete_old_document_versions(
+ filename,
+ document_id,
+ collection_name=collection_name,
+ )
def ingest(
recreate: bool = False,
collection_name: str | None = None,
- chunker: RecursiveCharacterTextSplitter | None = None,
+ chunker: Chunker | None = None,
chunk_size: int | None = None,
chunk_overlap: int | None = None,
) -> int:
pdfs = discover_pdfs()
+ if not pdfs:
+ logger.warning("No PDF files found in {}", settings.data_dir)
+ return 0
- ensure_collection(
- recreate=recreate,
- collection_name=collection_name,
- )
-
+ ensure_collection(recreate=recreate, collection_name=collection_name)
chunks = build_chunks(
- pdf_paths=pdfs,
+ pdfs,
chunker=chunker,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
)
- return index_chunks(
- chunks=chunks,
- collection_name=collection_name,
- )
+ if not chunks:
+ logger.warning("No chunks produced from {} PDF(s)", len(pdfs))
+ return 0
+ count = index_chunks(chunks, collection_name=collection_name)
+ _remove_stale_versions(chunks, collection_name=collection_name)
+ logger.info("Ingested {} chunks from {} PDF(s)", count, len(pdfs))
+ return count
-def save_and_ingest_pdf(
- file_bytes: bytes,
- filename: str,
- collection_name: str | None = None,
-) -> dict[str, str | int]:
+
+def save_and_ingest_pdf(file_bytes: bytes, filename: str) -> dict[str, object]:
+ """Save an uploaded PDF to `data_dir` and ingest it into Qdrant.
+
+ Args: file_bytes, filename. Returns: {"filename", "chunks_indexed"}. Raises: ValueError.
+ """
+ if not filename:
+ raise ValueError("Filename is required.")
+ if not filename.lower().endswith(".pdf"):
+ raise ValueError("Only PDF files are accepted.")
if not file_bytes:
raise ValueError("Uploaded file is empty.")
+ if len(file_bytes) > settings.max_upload_bytes:
+ raise ValueError(
+ f"PDF exceeds the {settings.max_upload_bytes // (1024 * 1024)} MiB upload limit."
+ )
+ if not file_bytes.startswith(_PDF_SIGNATURE):
+ raise ValueError("Uploaded content is not a PDF file.")
safe_name = Path(filename).name
-
- if not safe_name:
- raise ValueError("Filename cannot be empty.")
-
- if Path(safe_name).suffix.lower() != ".pdf":
- raise ValueError("Only PDF files are supported.")
-
- settings.data_dir.mkdir(
- parents=True,
- exist_ok=True,
- )
-
- destination = settings.data_dir / safe_name
- destination.write_bytes(file_bytes)
-
- ensure_collection(
- recreate=False,
- collection_name=collection_name,
- )
-
- chunks = build_chunks([destination])
-
- chunks_indexed = index_chunks(
- chunks=chunks,
- collection_name=collection_name,
- )
-
- return {
- "filename": safe_name,
- "document_id": _document_id(destination),
- "chunks_indexed": chunks_indexed,
- }
\ No newline at end of file
+ if safe_name in {"", ".", ".."}:
+ raise ValueError("Filename is invalid.")
+ settings.data_dir.mkdir(parents=True, exist_ok=True)
+ dest = settings.data_dir / safe_name
+ temporary_path: Path | None = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ dir=settings.data_dir,
+ prefix=".upload-",
+ suffix=".pdf",
+ delete=False,
+ ) as temporary:
+ temporary.write(file_bytes)
+ temporary_path = Path(temporary.name)
+
+ chunks = build_chunks(
+ [temporary_path],
+ filename_override=safe_name,
+ source_override=safe_name,
+ )
+ if not chunks:
+ raise ValueError("Uploaded PDF contains no indexable text.")
+
+ ensure_collection(recreate=False)
+ count = index_chunks(chunks)
+ document_id = str(chunks[0].metadata["document_id"])
+ os.replace(temporary_path, dest)
+ temporary_path = None
+ _remove_stale_versions(chunks)
+ logger.info("Saved and indexed {} chunks from {}", count, safe_name)
+ return {
+ "filename": safe_name,
+ "document_id": document_id,
+ "chunks_indexed": count,
+ }
+ finally:
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
diff --git a/src/interfaces/README.md b/src/interfaces/README.md
index bc0d74e420cd8046ad1027e05a54524841e09432..16df6c86b43d6dc0c08ccdb73052843bbc451a4b 100644
--- a/src/interfaces/README.md
+++ b/src/interfaces/README.md
@@ -1,8 +1,10 @@
-Interfaces
+# Interfaces
-The src/interfaces/ directory provides the system’s user-facing interfaces:
+- `api.py`: FastAPI routes for health, documents, upload, Q&A, summaries, quiz,
+ and flashcards.
+- `cli.py`: Typer CLI exposed as the `doculearn-rag` console command
+ (`notebooklm` remains as a compatibility alias).
+- `app.py` at the project root: Gradio web interface.
-* api.py — Implements a REST API using FastAPI.
-* cli.py — Provides a command-line interface.
-* ui.py — Builds the Streamlit web interface.
-* styles.py — Contains CSS styles for formatting the web interface.
\ No newline at end of file
+All interfaces call the same modules in `src` and share validation, filtering,
+indexing, retrieval, and generation behavior.
diff --git a/src/interfaces/api.py b/src/interfaces/api.py
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..d25476841247bc5a07ee9ad6c46db70619969713 100644
--- a/src/interfaces/api.py
+++ b/src/interfaces/api.py
@@ -0,0 +1,177 @@
+"""FastAPI entrypoint for the DocuLearn-RAG learning service."""
+
+from __future__ import annotations
+
+import secrets
+from typing import Annotated
+
+from fastapi import FastAPI as _FastAPI
+from fastapi import File, Header, HTTPException, UploadFile, status
+from pydantic import BaseModel, ConfigDict, Field
+from starlette.concurrency import run_in_threadpool
+
+from src.config import settings
+from src.filters import MetadataFilter, filters_to_dict
+from src.indexing import save_and_ingest_pdf
+from src.learning import generate_flashcards, generate_quiz
+from src.learning import summarize as summarize_learning
+from src.rag import answer
+from src.schemas import FlashcardSet, QuizSet, RagAnswer, Summary
+from src.store import list_documents
+
+
+class StrictRequest(BaseModel):
+ """Reject misspelled request fields instead of silently ignoring them."""
+
+ model_config = ConfigDict(extra="forbid")
+
+
+class AskRequest(StrictRequest):
+ question: str = Field(min_length=1)
+ k: int | None = Field(default=None, ge=1, le=64)
+ filters: MetadataFilter | None = None
+
+
+class SummarizeRequest(StrictRequest):
+ document: str | None = None
+ query: str | None = None
+ filters: MetadataFilter | None = None
+ k: int | None = Field(default=None, ge=1, le=64)
+
+
+class QuizRequest(SummarizeRequest):
+ count: int | None = Field(default=None, ge=1, le=50)
+
+
+class FlashcardsRequest(SummarizeRequest):
+ count: int | None = Field(default=None, ge=1, le=100)
+
+
+class HealthResponse(BaseModel):
+ status: str
+
+
+class DocumentInfo(BaseModel):
+ filename: str
+ document_id: str
+ pages: list[int]
+ page_count: int
+ chunk_count: int
+
+
+class UploadResponse(BaseModel):
+ filename: str
+ document_id: str
+ chunks_indexed: int
+
+
+app = _FastAPI(
+ title="DocuLearn-RAG API",
+ description="Grounded Q&A, summaries, quizzes, and flashcards over indexed PDFs.",
+ version="0.1.0",
+)
+
+
+def _require_api_key(x_api_key: Annotated[str | None, Header()] = None) -> None:
+ """Protect data and generation routes when RAG_API_KEY is configured."""
+ expected = settings.api_key
+ if expected is None:
+ return
+ if x_api_key is None or not secrets.compare_digest(x_api_key, expected):
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Missing or invalid API key.",
+ )
+
+
+@app.get("/health", response_model=HealthResponse)
+def health() -> HealthResponse:
+ return HealthResponse(status="ok")
+
+
+@app.get("/documents", response_model=list[DocumentInfo])
+def documents(
+ x_api_key: Annotated[str | None, Header()] = None,
+) -> list[dict[str, object]]:
+ _require_api_key(x_api_key)
+ return list_documents()
+
+
+@app.post("/upload", response_model=UploadResponse)
+async def upload(
+ file: Annotated[UploadFile, File()],
+ x_api_key: Annotated[str | None, Header()] = None,
+) -> dict[str, object]:
+ _require_api_key(x_api_key)
+ content = await file.read(settings.max_upload_bytes + 1)
+ if len(content) > settings.max_upload_bytes:
+ raise HTTPException(
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
+ detail=f"PDF exceeds the {settings.max_upload_bytes}-byte upload limit.",
+ )
+ try:
+ return await run_in_threadpool(save_and_ingest_pdf, content, file.filename or "")
+ except ValueError as exc:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
+ except (OSError, RuntimeError) as exc:
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail="The document could not be indexed.",
+ ) from exc
+
+
+@app.post("/ask", response_model=RagAnswer)
+def ask(
+ request: AskRequest,
+ x_api_key: Annotated[str | None, Header()] = None,
+) -> RagAnswer:
+ _require_api_key(x_api_key)
+ return answer(
+ request.question,
+ k=request.k,
+ filters=filters_to_dict(request.filters),
+ )
+
+
+@app.post("/summarize", response_model=Summary)
+def summarize(
+ request: SummarizeRequest,
+ x_api_key: Annotated[str | None, Header()] = None,
+) -> Summary:
+ _require_api_key(x_api_key)
+ return summarize_learning(
+ document=request.document,
+ query=request.query,
+ filters=filters_to_dict(request.filters),
+ k=request.k,
+ )
+
+
+@app.post("/quiz", response_model=QuizSet)
+def quiz(
+ request: QuizRequest,
+ x_api_key: Annotated[str | None, Header()] = None,
+) -> QuizSet:
+ _require_api_key(x_api_key)
+ return generate_quiz(
+ document=request.document,
+ query=request.query,
+ filters=filters_to_dict(request.filters),
+ count=request.count,
+ k=request.k,
+ )
+
+
+@app.post("/flashcards", response_model=FlashcardSet)
+def flashcards(
+ request: FlashcardsRequest,
+ x_api_key: Annotated[str | None, Header()] = None,
+) -> FlashcardSet:
+ _require_api_key(x_api_key)
+ return generate_flashcards(
+ document=request.document,
+ query=request.query,
+ filters=filters_to_dict(request.filters),
+ count=request.count,
+ k=request.k,
+ )
diff --git a/src/interfaces/cli.py b/src/interfaces/cli.py
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..3c24e897af32ee629307e4b566826d1cf92e7232 100644
--- a/src/interfaces/cli.py
+++ b/src/interfaces/cli.py
@@ -0,0 +1,182 @@
+"""Typer command-line entrypoint for DocuLearn-RAG."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import typer
+from pydantic import BaseModel, ValidationError
+
+from src.export import ExportFormat, export
+from src.filters import MetadataFilter, filters_to_dict
+from src.indexing import ingest as ingest_data
+from src.learning import generate_flashcards, generate_quiz
+from src.learning import summarize as summarize_learning
+from src.rag import answer, retrieve
+from src.schemas import RetrievedChunk
+
+app = typer.Typer(help="Index PDFs and use grounded DocuLearn-RAG learning features.")
+
+
+def _parse_filters(value: str | None) -> MetadataFilter | None:
+ if value is None or not value.strip():
+ return None
+
+ parsed: dict[str, object] = {}
+ allowed = set(MetadataFilter.model_fields)
+ for expression in value.split(","):
+ key, separator, raw_value = expression.partition("=")
+ key = key.strip()
+ raw_value = raw_value.strip()
+ if not separator or not key or not raw_value:
+ raise typer.BadParameter("Filters must use key=value pairs separated by commas.")
+ if key not in allowed:
+ raise typer.BadParameter(
+ f"Unknown filter '{key}'. Expected one of: {', '.join(sorted(allowed))}."
+ )
+ if key == "page":
+ try:
+ parsed[key] = int(raw_value)
+ except ValueError as error:
+ raise typer.BadParameter("The page filter must be an integer.") from error
+ elif key == "filenames":
+ parsed[key] = [item.strip() for item in raw_value.split("|") if item.strip()]
+ else:
+ parsed[key] = raw_value
+
+ try:
+ return MetadataFilter.model_validate(parsed)
+ except ValidationError as error:
+ raise typer.BadParameter(str(error)) from error
+
+
+def _write_result(
+ result: BaseModel,
+ output: Path | None,
+ fmt: ExportFormat,
+) -> None:
+ rendered = export(result, fmt=fmt, output=output)
+ if output is None:
+ typer.echo(rendered, nl=False)
+ else:
+ typer.echo(f"Exported to {rendered}")
+
+
+def _print_sources(chunks: list[RetrievedChunk]) -> None:
+ if not chunks:
+ return
+ typer.echo("\nSources:")
+ for index, chunk in enumerate(chunks, start=1):
+ metadata = chunk.metadata
+ typer.echo(f"S{index}: {metadata.filename}, page {metadata.page}")
+
+
+@app.command()
+def ingest(recreate: bool = False) -> None:
+ """Index all PDFs in the configured data directory."""
+ count = ingest_data(recreate=recreate)
+ typer.echo(f"Done. {count} chunks indexed.")
+
+
+@app.command()
+def ask(
+ question: str,
+ k: int | None = None,
+ filters: str | None = None,
+) -> None:
+ """Ask a grounded question and show its retrieved sources."""
+ result = answer(question, k=k, filters=filters_to_dict(_parse_filters(filters)))
+ typer.echo(result.answer)
+ _print_sources(result.chunks)
+
+
+@app.command("debug-retrieval")
+def debug_retrieval(
+ question: str,
+ k: int | None = None,
+ filters: str | None = None,
+ as_json: bool = False,
+) -> None:
+ """Inspect the chunks retrieved for a question."""
+ chunks = retrieve(question, k=k, filters=filters_to_dict(_parse_filters(filters)))
+ if as_json:
+ typer.echo(
+ json.dumps(
+ [chunk.model_dump(mode="json") for chunk in chunks],
+ ensure_ascii=False,
+ indent=2,
+ )
+ )
+ return
+ for index, chunk in enumerate(chunks, start=1):
+ metadata = chunk.metadata
+ typer.echo(
+ f"S{index} {metadata.filename} p.{metadata.page} "
+ f"score={chunk.score:.4f}\n{chunk.text}\n"
+ )
+
+
+@app.command()
+def summarize(
+ document: str | None = None,
+ query: str | None = None,
+ filters: str | None = None,
+ k: int | None = None,
+ output: Path | None = None,
+ fmt: ExportFormat = "text",
+) -> None:
+ """Create a grounded summary."""
+ result = summarize_learning(
+ document=document,
+ query=query,
+ filters=filters_to_dict(_parse_filters(filters)),
+ k=k,
+ )
+ _write_result(result, output, fmt)
+
+
+@app.command()
+def quiz(
+ document: str | None = None,
+ query: str | None = None,
+ filters: str | None = None,
+ count: int | None = None,
+ k: int | None = None,
+ output: Path | None = None,
+ fmt: ExportFormat = "text",
+) -> None:
+ """Generate a grounded multiple-choice quiz."""
+ result = generate_quiz(
+ document=document,
+ query=query,
+ filters=filters_to_dict(_parse_filters(filters)),
+ count=count,
+ k=k,
+ )
+ _write_result(result, output, fmt)
+
+
+@app.command()
+def flashcards(
+ document: str | None = None,
+ query: str | None = None,
+ filters: str | None = None,
+ count: int | None = None,
+ k: int | None = None,
+ output: Path | None = None,
+ fmt: ExportFormat = "text",
+) -> None:
+ """Generate grounded flashcards."""
+ result = generate_flashcards(
+ document=document,
+ query=query,
+ filters=filters_to_dict(_parse_filters(filters)),
+ count=count,
+ k=k,
+ )
+ _write_result(result, output, fmt)
+
+
+if __name__ == "__main__":
+ app()
diff --git a/src/interfaces/styles.py b/src/interfaces/styles.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/src/interfaces/ui.py b/src/interfaces/ui.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/src/learning.py b/src/learning.py
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..5a3606d6458e57634aed7ce78a24b19f0efa73f0 100644
--- a/src/learning.py
+++ b/src/learning.py
@@ -0,0 +1,233 @@
+"""Grounded learning features: summarization, quiz, and flashcard generation."""
+
+from __future__ import annotations
+
+import json
+from typing import Literal
+
+from loguru import logger
+from pydantic import ValidationError
+
+from src.config import settings
+from src.llm import invoke_llm
+from src.rag import fetch_all_chunks, format_citations, render_prompt, retrieve
+from src.schemas import Flashcard, FlashcardSet, QuizItem, QuizSet, RetrievedChunk, Summary
+
+SUMMARY_SINGLE_TEMPLATE = "summary_single.jinja2"
+SUMMARY_MAP_TEMPLATE = "summary_map.jinja2"
+SUMMARY_REDUCE_TEMPLATE = "summary_reduce.jinja2"
+QUIZ_TEMPLATE = "quiz.jinja2"
+FLASHCARDS_TEMPLATE = "flashcards.jinja2"
+
+
+Scope = Literal["query", "document", "filter", "corpus"]
+
+
+def _parse_json(text: str) -> dict[str, object] | list[object]:
+ """Parse JSON object/array from model output, allowing optional markdown code fences."""
+ cleaned = text.strip()
+ if cleaned.startswith("```"):
+ cleaned = cleaned.split("\n", 1)[-1].removesuffix("```").strip()
+
+ try:
+ obj = json.loads(cleaned)
+ except json.JSONDecodeError as e:
+ raise RuntimeError(f"Invalid JSON from model output: {cleaned}") from e
+
+ if not isinstance(obj, (dict, list)):
+ raise RuntimeError(f"Expected JSON object or array, got {type(obj).__name__}.")
+
+ return obj
+
+
+def _resolve_target(
+ document: str | None,
+ query: str | None,
+ filters: dict[str, object] | None,
+ k: int | None,
+ retrieval_k: int,
+) -> tuple[list[RetrievedChunk], Scope, str | None]:
+ """Resolve input options into (chunks, scope, target_label)."""
+ effective_filters: dict[str, object] = dict(filters or {})
+ if document:
+ effective_filters["filename"] = document
+
+ if query:
+ chunks = retrieve(query, k=k or retrieval_k, filters=effective_filters)
+ target: str | None = query
+ scope = "query"
+ elif effective_filters:
+ chunks = fetch_all_chunks(filters=effective_filters)
+ target = ", ".join(f"{fk}={fv}" for fk, fv in effective_filters.items())
+ scope = "document" if document else "filter"
+ else:
+ chunks = fetch_all_chunks(filters=None)
+ target = None
+ scope = "corpus"
+
+ return chunks, scope, target
+
+
+def _validate_items[LearningItem: (QuizItem, Flashcard)](
+ payload: object,
+ key: str,
+ model_class: type[LearningItem],
+ dedup_field: str,
+ label: str,
+ valid_markers: set[str],
+) -> list[LearningItem]:
+ if not isinstance(payload, dict):
+ raise RuntimeError(f"Expected JSON object for {label}.")
+ raw_items = payload.get(key)
+ if not isinstance(raw_items, list):
+ raise RuntimeError(f"Expected '{key}' to be a list for {label}.")
+
+ items: list[LearningItem] = []
+ seen: set[str] = set()
+ for raw in raw_items:
+ if not isinstance(raw, dict):
+ continue
+ try:
+ item = model_class.model_validate(raw)
+ except ValidationError as e:
+ logger.warning("Dropping invalid {}: {}", label, e)
+ continue
+ norm = str(getattr(item, dedup_field, "")).strip().lower()
+ if not norm or norm in seen:
+ continue
+ seen.add(norm)
+ markers = [m for m in item.source_markers if m in valid_markers]
+ if not markers:
+ logger.warning("Dropping ungrounded {} without a valid source marker", label)
+ continue
+ items.append(item.model_copy(update={"source_markers": markers}))
+
+ if not items:
+ raise RuntimeError(f"No valid {label} produced.")
+ return items
+
+
+def _validate_summary_payload(payload: object) -> tuple[str, list[str]]:
+ if not isinstance(payload, dict):
+ raise RuntimeError("Expected a JSON object for summary.")
+ summary = payload.get("summary")
+ key_points = payload.get("key_points", [])
+ if not isinstance(summary, str):
+ raise RuntimeError("Summary payload missing 'summary' string.")
+ if not isinstance(key_points, list) or not all(isinstance(x, str) for x in key_points):
+ raise RuntimeError("Summary payload 'key_points' must be a list of strings.")
+ return summary.strip(), [kp.strip() for kp in key_points if kp.strip()]
+
+
+def summarize(
+ document: str | None = None,
+ query: str | None = None,
+ filters: dict[str, object] | None = None,
+ k: int | None = None,
+) -> Summary:
+ """Grounded summary; uses map-reduce when chunk count exceeds batch size."""
+ chunks, scope, target = _resolve_target(
+ document=document,
+ query=query,
+ filters=filters,
+ k=k,
+ retrieval_k=settings.summarize_retrieval_k,
+ )
+
+ if not chunks:
+ raise RuntimeError("No chunks available for summarization.")
+
+ batch_size = settings.summarize_batch_size
+ if len(chunks) <= batch_size:
+ prompt = render_prompt(SUMMARY_SINGLE_TEMPLATE, chunks=chunks)
+ payload = _parse_json(invoke_llm(prompt))
+ summary_text, key_points = _validate_summary_payload(payload)
+ else:
+ n_batches = (len(chunks) + batch_size - 1) // batch_size
+ partials: list[dict[str, object]] = []
+
+ for batch_index, start in enumerate(range(0, len(chunks), batch_size), start=1):
+ logger.info("Summarizing batch {}/{}", batch_index, n_batches)
+ batch = chunks[start : start + batch_size]
+ prompt = render_prompt(SUMMARY_MAP_TEMPLATE, chunks=batch)
+ payload = _parse_json(invoke_llm(prompt))
+ summary_text, key_points = _validate_summary_payload(payload)
+ partials.append({"summary": summary_text, "key_points": key_points})
+
+ reduce_prompt = render_prompt(SUMMARY_REDUCE_TEMPLATE, partials=partials)
+ payload = _parse_json(invoke_llm(reduce_prompt))
+ summary_text, key_points = _validate_summary_payload(payload)
+
+ return Summary(
+ scope=scope,
+ target=target,
+ summary=summary_text,
+ key_points=key_points,
+ citations=format_citations(chunks),
+ )
+
+
+def generate_quiz(
+ document: str | None = None,
+ query: str | None = None,
+ filters: dict[str, object] | None = None,
+ count: int | None = None,
+ k: int | None = None,
+) -> QuizSet:
+ """Grounded multiple-choice quiz; raises RuntimeError if output is unparseable."""
+ chunks, scope, target = _resolve_target(
+ document=document,
+ query=query,
+ filters=filters,
+ k=k,
+ retrieval_k=settings.generation_retrieval_k,
+ )
+ if not chunks:
+ raise RuntimeError("No chunks available for quiz generation.")
+
+ n = count or settings.quiz_default_count
+ valid_markers = {f"S{i}" for i in range(1, len(chunks) + 1)}
+
+ prompt = render_prompt(QUIZ_TEMPLATE, chunks=chunks, count=n)
+ payload = _parse_json(invoke_llm(prompt))
+ items = _validate_items(payload, "items", QuizItem, "question", "quiz items", valid_markers)
+
+ return QuizSet(
+ scope=scope,
+ target=target,
+ items=items,
+ citations=format_citations(chunks),
+ )
+
+
+def generate_flashcards(
+ document: str | None = None,
+ query: str | None = None,
+ filters: dict[str, object] | None = None,
+ count: int | None = None,
+ k: int | None = None,
+) -> FlashcardSet:
+ """Generate grounded flashcards, rejecting unparseable model output."""
+ chunks, scope, target = _resolve_target(
+ document=document,
+ query=query,
+ filters=filters,
+ k=k,
+ retrieval_k=settings.generation_retrieval_k,
+ )
+ if not chunks:
+ raise RuntimeError("No chunks available for flashcard generation.")
+
+ n = count or settings.flashcards_default_count
+ valid_markers = {f"S{i}" for i in range(1, len(chunks) + 1)}
+
+ prompt = render_prompt(FLASHCARDS_TEMPLATE, chunks=chunks, count=n)
+ payload = _parse_json(invoke_llm(prompt))
+ cards = _validate_items(payload, "cards", Flashcard, "front", "flashcards", valid_markers)
+
+ return FlashcardSet(
+ scope=scope,
+ target=target,
+ cards=cards,
+ citations=format_citations(chunks),
+ )
diff --git a/src/llm.py b/src/llm.py
index fb761898edcd15b4e4a26c5e1373131fe45245a4..fa104764e33b373101dcb27319255a2b6449ef7c 100644
--- a/src/llm.py
+++ b/src/llm.py
@@ -1,63 +1,42 @@
-from functools import lru_cache
-from typing import Any, Literal
+"""LLM invocation through Gemini API (google-genai)."""
-from langchain_core.messages import HumanMessage
-from langchain_core.language_models.chat_models import BaseChatModel
-from langchain_google_genai import ChatGoogleGenerativeAI
-from langchain_openai import ChatOpenAI
+from __future__ import annotations
-from config import settings
+from contextvars import ContextVar
+from google import genai
+from google.genai import types
+from src.config import settings
-def _build_hf_local():
- import torch
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
- from langchain_huggingface import ChatHuggingFace, HuggingFacePipeline
+_runtime_api_key: ContextVar[str | None] = ContextVar("runtime_gemini_api_key", default=None)
- tokenizer = AutoTokenizer.from_pretrained(settings.hf_model)
- model = AutoModelForCausalLM.from_pretrained(settings.hf_model, dtype=torch.bfloat16)
- text_gen = pipeline(
- task="text-generation",
- model=model,
- tokenizer=tokenizer,
- device=settings.hf_device,
- return_full_text=False,
- )
- text_gen.generation_config.max_new_tokens = settings.hf_max_new_tokens
- text_gen.generation_config.do_sample = settings.llm_temperature > 0
+def set_runtime_gemini_api_key(api_key: str | None) -> None:
+ _runtime_api_key.set(api_key.strip() if isinstance(api_key, str) else None)
- return ChatHuggingFace(llm=HuggingFacePipeline(pipeline=text_gen))
-def _build_gemini():
- return ChatGoogleGenerativeAI(
- model=settings.gemini_model,
- temperature=settings.llm_temperature,
- google_api_key=settings.google_api_key,
- )
+def invoke_llm(prompt: str) -> str:
+ """Invoke the configured chat model and return plain text.
+
+ Args: prompt.
+ Returns: assistant text content.
+ Raises: RuntimeError if the API key is missing or response is empty.
+ """
+ api_key = _runtime_api_key.get() or settings.gemini_api_key
+ if not api_key:
+ raise RuntimeError("Missing Gemini API key. Provide it in the UI or set GEMINI_API_KEY.")
-def _build_vllm():
- return ChatOpenAI(
- model=settings.hf_model,
- openai_api_key=settings.vllm_api_key,
- openai_api_base=settings.vllm_api_base,
- temperature=settings.llm_temperature,
+ client = genai.Client(api_key=api_key)
+ resp = client.models.generate_content(
+ model=settings.llm_model,
+ contents=prompt,
+ config=types.GenerateContentConfig(
+ temperature=settings.llm_temperature,
+ max_output_tokens=settings.llm_max_new_tokens,
+ ),
)
-
-@lru_cache(maxsize=4)
-def get_llm(provider=None):
- provider = provider or settings.llm_provider
-
- if provider == "hf_local":
- return _build_hf_local()
- if provider == "gemini":
- return _build_gemini()
- if provider == "vllm":
- return _build_vllm()
-
- raise ValueError(f"Unknown llm_provider '{provider}'")
-
-def invoke_llm(prompt, provider=None):
- response = get_llm(provider=provider).invoke([HumanMessage(content=prompt)])
- return response.content if isinstance(response.content, str) else str(response.content)
\ No newline at end of file
+ text = (resp.text or "").strip()
+ if not text:
+ raise RuntimeError("Empty response from Gemini.")
+ return text
diff --git a/src/prompts/answer.jinja2 b/src/prompts/answer.jinja2
new file mode 100644
index 0000000000000000000000000000000000000000..bf814eaff374c467cf1b2babcb6b762972feb836
--- /dev/null
+++ b/src/prompts/answer.jinja2
@@ -0,0 +1,22 @@
+You are a precise assistant. Answer the user's question using ONLY the context below.
+
+Rules:
+- Use only facts explicitly supported by the context. Do not invent details.
+- If the context is insufficient, reply exactly: "Tôi không có đủ thông tin trong ngữ cảnh được cung cấp để trả lời."
+- Be concise and direct.
+- Write your answer in Vietnamese.
+- Cite support inline using source markers like [S1], [S2].
+- Use only the source markers provided in the context.
+- Do not write filenames, page numbers, or chunk IDs in the answer body.
+
+Context:
+{% for c in chunks %}
+---
+[source={{ "S" ~ loop.index }}]
+{{ c.text }}
+{% endfor %}
+
+Question: {{ question }}
+
+Answer:
+
diff --git a/src/prompts/flashcards.jinja2 b/src/prompts/flashcards.jinja2
new file mode 100644
index 0000000000000000000000000000000000000000..969d596547e5e4fbaf74af12a6f605c15fb8eef5
--- /dev/null
+++ b/src/prompts/flashcards.jinja2
@@ -0,0 +1,35 @@
+You are generating study flashcards grounded in the provided context.
+
+Rules:
+- Generate exactly {{ count }} flashcards.
+- Fronts should ask for a concept, term, distinction, formula, process, or short explanation.
+- Backs must be concise but complete enough for revision.
+- Ground every card in the context. Do not invent facts.
+- Avoid low-value cards that only restate section headings.
+- Avoid duplicate or overly similar cards.
+- Provide at least one [S#] source marker per card when possible.
+- If the context is insufficient for {{ count }} useful cards, produce fewer rather than pad.
+- Write all fronts, backs, hints, and topic labels in Vietnamese.
+
+Output STRICTLY valid JSON and no other text, with this exact shape:
+{
+ "cards": [
+ {
+ "front": "string",
+ "back": "string",
+ "hint": "optional string or null",
+ "topic": "optional short topic label or null",
+ "source_markers": ["S1"]
+ }
+ ]
+}
+
+Context:
+{% for c in chunks %}
+---
+[source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
+{{ c.text }}
+{% endfor %}
+
+Respond with ONLY the JSON object.
+
diff --git a/src/prompts/quiz.jinja2 b/src/prompts/quiz.jinja2
new file mode 100644
index 0000000000000000000000000000000000000000..4d5e1ec8b0e80c6b63a93280ae4b85feaa41fc9d
--- /dev/null
+++ b/src/prompts/quiz.jinja2
@@ -0,0 +1,37 @@
+You are generating high-quality multiple-choice quiz items grounded in the provided context.
+
+Rules:
+- Generate exactly {{ count }} items.
+- Every question must be answerable from the context alone.
+- Provide exactly 4 options per question with exactly one correct answer.
+- Test understanding: concepts, distinctions, reasoning, and factual recall.
+- Avoid duplicates or near-duplicates.
+- Avoid trick questions or ambiguous wording.
+- Explanations must be concise and cite at least one [S#] marker from the context.
+- If the context is insufficient to create {{ count }} high-quality items, generate fewer. Never fabricate facts.
+- Write all questions, options, explanations, and topic labels in Vietnamese.
+
+Output STRICTLY valid JSON and no other text, with this exact shape:
+{
+ "items": [
+ {
+ "question": "string",
+ "options": ["string", "string", "string", "string"],
+ "correct_index": 0,
+ "explanation": "grounded explanation with [S1] style citations",
+ "source_markers": ["S1"],
+ "difficulty": "easy|medium|hard",
+ "topic": "short topic label"
+ }
+ ]
+}
+
+Context:
+{% for c in chunks %}
+---
+[source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
+{{ c.text }}
+{% endfor %}
+
+Respond with ONLY the JSON object.
+
diff --git a/src/prompts/summary_map.jinja2 b/src/prompts/summary_map.jinja2
new file mode 100644
index 0000000000000000000000000000000000000000..37a5c7dc2729f0baec690b604b2f60981bbac3b3
--- /dev/null
+++ b/src/prompts/summary_map.jinja2
@@ -0,0 +1,24 @@
+You are summarizing a portion of a learning document for later synthesis.
+
+Rules:
+- Summarize only what the passages actually say.
+- Preserve concepts, definitions, processes, and reasoning.
+- Do not add outside knowledge. Do not speculate.
+- Keep it dense but readable; aim for 4-8 sentences.
+- Write the summary and key points in Vietnamese.
+
+Output STRICTLY valid JSON with this shape and no extra text:
+{
+ "summary": "dense paragraph summary",
+ "key_points": ["fact", "fact"]
+}
+
+Passages:
+{% for c in chunks %}
+---
+[source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
+{{ c.text }}
+{% endfor %}
+
+Respond with ONLY the JSON object.
+
diff --git a/src/prompts/summary_reduce.jinja2 b/src/prompts/summary_reduce.jinja2
new file mode 100644
index 0000000000000000000000000000000000000000..353f3ca194896ac5673de90aebe0b76ee168b9fa
--- /dev/null
+++ b/src/prompts/summary_reduce.jinja2
@@ -0,0 +1,29 @@
+You are synthesizing partial summaries of a learning document into one coherent study summary.
+
+Rules:
+- Use only information present in the partial summaries.
+- Do not add outside knowledge. Do not invent details.
+- Merge duplicated points; preserve distinctions between related concepts.
+- Write for a learner who wants to understand and remember the material.
+- Write the summary and key points in Vietnamese.
+
+Output STRICTLY valid JSON with this shape and no extra text:
+{
+ "summary": "A coherent multi-paragraph study summary.",
+ "key_points": ["concise learnable fact", "concise learnable fact"]
+}
+
+Partial summaries:
+{% for p in partials %}
+---
+Summary: {{ p.summary }}
+{% if p.key_points %}
+Key points:
+{% for kp in p.key_points %}
+- {{ kp }}
+{% endfor %}
+{% endif %}
+{% endfor %}
+
+Respond with ONLY the JSON object.
+
diff --git a/src/prompts/summary_single.jinja2 b/src/prompts/summary_single.jinja2
new file mode 100644
index 0000000000000000000000000000000000000000..a435b58678b7ded46ffbe5e475b7fa1922952daf
--- /dev/null
+++ b/src/prompts/summary_single.jinja2
@@ -0,0 +1,25 @@
+You are writing a study-oriented summary grounded strictly in the provided context.
+
+Rules:
+- Use only facts explicitly supported by the context. Do not invent details.
+- Do not add outside knowledge.
+- Focus on concepts, definitions, relationships, and reasoning a learner should retain.
+- Keep the tone clear, neutral, and practical for study.
+- Write the summary and key points in Vietnamese.
+- If the context is empty or unrelated, return an empty summary and an empty list of key points.
+
+Output STRICTLY valid JSON with this shape and no extra text:
+{
+ "summary": "A coherent multi-paragraph study summary.",
+ "key_points": ["concise learnable fact", "concise learnable fact"]
+}
+
+Context:
+{% for c in chunks %}
+---
+[source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
+{{ c.text }}
+{% endfor %}
+
+Respond with ONLY the JSON object.
+
diff --git a/src/rag.py b/src/rag.py
index 37893508e6281197747be67ee20579e2d90a9d40..3efad7caa1cdd9765f61d1543dab7d90025a64ae 100644
--- a/src/rag.py
+++ b/src/rag.py
@@ -1,122 +1,67 @@
+"""Retrieval, prompts, citations, and grounded answers."""
+
+from __future__ import annotations
+
from functools import lru_cache
-from typing import Any
+from pathlib import Path
from jinja2 import Environment, FileSystemLoader, StrictUndefined
-from pydantic import ValidationError
-from config import settings
-from schemas import (
- ChunkMetadata,
- Citation,
- RagAnswer,
- RetrievedChunk,
-)
+from src.config import settings
+from src.filters import filters_to_qdrant
+from src.llm import invoke_llm
+from src.schemas import ChunkMetadata, Citation, RagAnswer, RetrievedChunk
+from src.store import get_vector_store, scroll_all
+
+PROMPTS_DIR = Path(__file__).parent / "prompts"
+ANSWER_TEMPLATE = "answer.jinja2"
def retrieve(
query: str,
k: int | None = None,
- filters: Any = None,
+ filters: dict[str, object] | None = None,
collection_name: str | None = None,
) -> list[RetrievedChunk]:
- query = query.strip()
-
- if not query:
- raise ValueError("query cannot be empty.")
-
- resolved_k = settings.top_k if k is None else k
-
- if resolved_k <= 0:
- raise ValueError("k must be greater than 0.")
-
- hits = get_vector_store(
- collection_name=collection_name
- ).similarity_search_with_score(
+ store = get_vector_store(collection_name=collection_name)
+ hits = store.similarity_search_with_score(
query=query,
- k=resolved_k,
+ k=k or settings.top_k,
filter=filters_to_qdrant(filters),
)
-
- results: list[RetrievedChunk] = []
-
- for document, score in hits:
- metadata = ChunkMetadata.model_validate(
- document.metadata
- )
-
- results.append(
- RetrievedChunk(
- text=document.page_content,
- score=float(score),
- metadata=metadata,
- )
+ return [
+ RetrievedChunk(
+ text=doc.page_content,
+ score=float(score),
+ metadata=ChunkMetadata(**doc.metadata),
)
-
- return results
-
-
-def _chunk_index(chunk_id: str) -> int:
- try:
- return int(chunk_id.rsplit(":", 1)[-1])
- except (TypeError, ValueError):
- # Đẩy chunk có ID không hợp lệ xuống cuối.
- return 2**31 - 1
+ for doc, score in hits
+ ]
def fetch_all_chunks(
- filters: Any = None,
+ filters: dict[str, object] | None = None,
collection_name: str | None = None,
) -> list[RetrievedChunk]:
+ """Scroll every chunk matching the filter, ordered by filename → page → index."""
name = collection_name or settings.qdrant_collection
- qdrant_filter = filters_to_qdrant(filters)
-
results: list[RetrievedChunk] = []
-
- for points in scroll_all(
- name,
- scroll_filter=qdrant_filter,
- ):
- for point in points:
+ for page in scroll_all(name, scroll_filter=filters_to_qdrant(filters)):
+ for point in page:
payload = point.payload or {}
-
- metadata_payload = payload.get("metadata")
- text_payload = payload.get("page_content")
-
- if not isinstance(metadata_payload, dict):
- continue
-
- if not isinstance(text_payload, str):
+ meta = payload.get("metadata") or {}
+ text = payload.get("page_content") or ""
+ if not meta or not text:
continue
-
- text = text_payload.strip()
-
- if not text:
- continue
-
- try:
- metadata = ChunkMetadata.model_validate(
- metadata_payload
- )
- except ValidationError:
- # Nên log dữ liệu lỗi trong ứng dụng thực tế.
- continue
-
- results.append(
- RetrievedChunk(
- text=text,
- score=0.0,
- metadata=metadata,
- )
- )
-
- return sorted(
- results,
- key=lambda result: (
- result.metadata.filename.casefold(),
- result.metadata.page,
- _chunk_index(result.metadata.chunk_id),
- ),
+ results.append(RetrievedChunk(text=text, score=0.0, metadata=ChunkMetadata(**meta)))
+ results.sort(
+ key=lambda r: (
+ r.metadata.filename,
+ r.metadata.page,
+ int(r.metadata.chunk_id.rsplit(":", 1)[-1]),
+ )
)
+ return results
@lru_cache(maxsize=1)
@@ -130,89 +75,45 @@ def _jinja_env() -> Environment:
)
-def render_prompt(
- template_name: str,
- **context: Any,
-) -> str:
- return (
- _jinja_env()
- .get_template(template_name)
- .render(**context)
- )
+def render_prompt(template_name: str, **context: object) -> str:
+ """Render an arbitrary Jinja template from the prompts directory."""
+ return _jinja_env().get_template(template_name).render(**context)
-def format_citations(
- chunks: list[RetrievedChunk],
-) -> list[Citation]:
+def format_citations(chunks: list[RetrievedChunk]) -> list[Citation]:
return [
Citation(
- source_index=index,
- source_marker=f"S{index}",
- filename=chunk.metadata.filename,
- page=chunk.metadata.page,
- section=chunk.metadata.section,
- chunk_id=chunk.metadata.chunk_id,
- )
- for index, chunk in enumerate(
- chunks,
- start=1,
+ source_index=i,
+ source_marker=f"S{i}",
+ filename=c.metadata.filename,
+ page=c.metadata.page,
+ source_text=c.text.strip(),
+ section=c.metadata.section,
+ chunk_id=c.metadata.chunk_id,
)
+ for i, c in enumerate(chunks, start=1)
]
def answer(
question: str,
k: int | None = None,
- filters: Any = None,
+ filters: dict[str, object] | None = None,
collection_name: str | None = None,
) -> RagAnswer:
- question = question.strip()
-
- if not question:
- raise ValueError("question cannot be empty.")
-
- chunks = retrieve(
- query=question,
- k=k,
- filters=filters,
- collection_name=collection_name,
- )
-
+ chunks = retrieve(question, k=k, filters=filters, collection_name=collection_name)
if not chunks:
return RagAnswer(
question=question,
- answer=(
- "Tôi không có đủ thông tin trong ngữ cảnh "
- "được cung cấp để trả lời."
- ),
- citations=[],
- chunks=[],
- )
-
- prompt = render_prompt(
- ANSWER_TEMPLATE,
- question=question,
- chunks=chunks,
- )
-
- response = invoke_llm(prompt)
-
- if not isinstance(response, str):
- raise TypeError(
- "invoke_llm() must return a string."
+ answer="Tôi không có đủ thông tin trong ngữ cảnh được cung cấp để trả lời.",
)
- answer_text = response.strip()
-
- if not answer_text:
- answer_text = (
- "Tôi không có đủ thông tin trong ngữ cảnh "
- "được cung cấp để trả lời."
- )
+ prompt = render_prompt(ANSWER_TEMPLATE, question=question, chunks=chunks)
+ text = invoke_llm(prompt)
return RagAnswer(
question=question,
- answer=answer_text,
+ answer=text.strip(),
citations=format_citations(chunks),
chunks=chunks,
- )
\ No newline at end of file
+ )
diff --git a/src/schemas.py b/src/schemas.py
index 54494552fe1aed1054c08bb929c7f49e7249974b..d5831d96e6bd861f38b79172c512215700e772fd 100644
--- a/src/schemas.py
+++ b/src/schemas.py
@@ -1,77 +1,94 @@
+"""Pydantic schemas for chunks, answers, and learning outputs."""
+
+from __future__ import annotations
+
from typing import Literal
from pydantic import BaseModel, Field, model_validator
+
class ChunkMetadata(BaseModel):
+ """Stable metadata attached to every chunk stored in Qdrant."""
+
document_id: str
filename: str
source: str
- page: int = Field(ge=0)
+ page: int
chunk_id: str
section: str | None = None
+
class RetrievedChunk(BaseModel):
+ """A retrieved chunk with its score and metadata."""
+
text: str
score: float
metadata: ChunkMetadata
+
class Citation(BaseModel):
- source_index: int = Field(ge=0)
+ """Citation extracted from a retrieved chunk's metadata."""
+
+ source_index: int
source_marker: str
filename: str
- page: int | None = Field(default=None, ge=0)
+ page: int
+ source_text: str | None = None
section: str | None = None
chunk_id: str | None = None
+
class RagAnswer(BaseModel):
+ """Final grounded answer returned to the caller."""
+
question: str
answer: str
citations: list[Citation] = Field(default_factory=list)
chunks: list[RetrievedChunk] = Field(default_factory=list)
+
class Summary(BaseModel):
+ """Grounded study-oriented summary of a document or subset."""
+
scope: Literal["query", "document", "filter", "corpus"]
target: str | None = None
summary: str
key_points: list[str] = Field(default_factory=list)
citations: list[Citation] = Field(default_factory=list)
- chunks: list[RetrievedChunk] = Field(default_factory=list)
class QuizItem(BaseModel):
- question: str
-
- options: list[str] = Field(
- min_length=4,
- max_length=4,
- )
+ """A single multiple-choice quiz item grounded in the source material."""
+ question: str
+ options: list[str] = Field(min_length=4, max_length=4)
correct_index: int
explanation: str
source_markers: list[str] = Field(default_factory=list)
-
- difficulty: Literal["easy", "medium", "hard"] | None = None
+ difficulty: str | None = None
topic: str | None = None
@model_validator(mode="after")
- def validate_correct_index(self) -> "QuizItem":
+ def _validate_correct_index(self) -> QuizItem:
if not 0 <= self.correct_index < len(self.options):
raise ValueError(
- "correct_index must refer to an existing option."
+ f"correct_index {self.correct_index} out of range for {len(self.options)} options"
)
-
return self
class QuizSet(BaseModel):
+ """A reusable set of grounded quiz items with resolved citations."""
+
scope: Literal["query", "document", "filter", "corpus"]
target: str | None = None
items: list[QuizItem] = Field(default_factory=list)
citations: list[Citation] = Field(default_factory=list)
- chunks: list[RetrievedChunk] = Field(default_factory=list)
class Flashcard(BaseModel):
+ """A single study flashcard grounded in the source material."""
+
front: str
back: str
hint: str | None = None
@@ -80,8 +97,9 @@ class Flashcard(BaseModel):
class FlashcardSet(BaseModel):
+ """A reusable set of grounded flashcards with resolved citations."""
+
scope: Literal["query", "document", "filter", "corpus"]
target: str | None = None
cards: list[Flashcard] = Field(default_factory=list)
citations: list[Citation] = Field(default_factory=list)
- chunks: list[RetrievedChunk] = Field(default_factory=list)
\ No newline at end of file
diff --git a/src/store.py b/src/store.py
index eb965406febe8eb327fde70a9f1121201ac6ed19..9bec54fa8207e8f0798f186f6ae6124ef81e2a8d 100644
--- a/src/store.py
+++ b/src/store.py
@@ -1,94 +1,188 @@
+"""Embeddings, Qdrant client, collection setup, and vector store."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
from functools import lru_cache
-from langchain_huggingface import HuggingFaceEmbeddings
from langchain_qdrant import QdrantVectorStore
from qdrant_client import QdrantClient
-from qdrant_client import models as qmodels
-
-from config import settings
+from qdrant_client.http import models as qmodels
+from src.config import settings
+from src.embeddings import get_embeddings
-@lru_cache(maxsize=1)
-def get_embeddings() -> HuggingFaceEmbeddings:
- return HuggingFaceEmbeddings(
- model_name=settings.embedding_model,
- model_kwargs={
- "device": settings.hf_device,
- },
- encode_kwargs={
- "normalize_embeddings": True,
- },
- )
+_SCROLL_PAGE_SIZE = 256
+INDEXED_PAYLOAD_FIELDS = {
+ "metadata.document_id": qmodels.PayloadSchemaType.KEYWORD,
+ "metadata.filename": qmodels.PayloadSchemaType.KEYWORD,
+ "metadata.page": qmodels.PayloadSchemaType.INTEGER,
+}
-@lru_cache(maxsize=1)
-def get_client() -> QdrantClient:
- settings.storage_dir.mkdir(
- parents=True,
- exist_ok=True,
- )
- return QdrantClient(
- path=str(settings.storage_dir),
+def _old_document_versions_filter(
+ filename: str,
+ keep_document_id: str,
+) -> qmodels.Filter:
+ """Select older vector versions for one uploaded filename."""
+ return qmodels.Filter(
+ must=[
+ qmodels.FieldCondition(
+ key="metadata.filename",
+ match=qmodels.MatchValue(value=filename),
+ )
+ ],
+ must_not=[
+ qmodels.FieldCondition(
+ key="metadata.document_id",
+ match=qmodels.MatchValue(value=keep_document_id),
+ )
+ ],
)
-def get_vector_store(
+def delete_old_document_versions(
+ filename: str,
+ keep_document_id: str,
collection_name: str | None = None,
-) -> QdrantVectorStore:
+) -> None:
+ """Delete stale vectors for a filename after its new version is indexed."""
name = collection_name or settings.qdrant_collection
-
- return QdrantVectorStore(
- client=get_client(),
+ get_client().delete(
collection_name=name,
- embedding=get_embeddings(),
+ points_selector=qmodels.FilterSelector(
+ filter=_old_document_versions_filter(filename, keep_document_id)
+ ),
+ wait=True,
)
-INDEXED_PAYLOAD_FIELDS: dict[str, qmodels.PayloadSchemaType] = {
- "metadata.document_id": qmodels.PayloadSchemaType.KEYWORD,
- "metadata.filename": qmodels.PayloadSchemaType.KEYWORD,
- "metadata.chunk_id": qmodels.PayloadSchemaType.KEYWORD,
- "metadata.page": qmodels.PayloadSchemaType.INTEGER,
-}
+def close_client() -> None:
+ if get_client.cache_info().currsize == 0:
+ return
+ client = get_client()
+ client.close()
+ get_client.cache_clear()
-def ensure_collection(
- recreate: bool = False,
- collection_name: str | None = None,
-) -> None:
+@lru_cache(maxsize=1)
+def get_client() -> QdrantClient:
+ """Return a cached local Qdrant client backed by on-disk storage."""
+ settings.storage_dir.mkdir(parents=True, exist_ok=True)
+ return QdrantClient(path=str(settings.storage_dir))
+
+
+def ensure_collection(recreate: bool = False, collection_name: str | None = None) -> None:
+ """Create the collection and payload indexes if they do not exist."""
client = get_client()
name = collection_name or settings.qdrant_collection
- exists = client.collection_exists(
- collection_name=name,
- )
-
+ exists = client.collection_exists(name)
if exists and recreate:
- client.delete_collection(
- collection_name=name,
- )
+ client.delete_collection(name)
exists = False
if not exists:
- embedding_dimension = len(get_embeddings().embed_query("dimension probe"))
-
+ dim = len(get_embeddings().embed_query("dimension probe"))
client.create_collection(
collection_name=name,
vectors_config=qmodels.VectorParams(
- size=embedding_dimension,
+ size=dim,
distance=qmodels.Distance.COSINE,
),
)
- collection_info = client.get_collection(collection_name=name)
-
- payload_schema = collection_info.payload_schema or {}
+ payload_schema = client.get_collection(name).payload_schema or {}
for field_name, field_schema in INDEXED_PAYLOAD_FIELDS.items():
- if field_name not in payload_schema:
+ existing = payload_schema.get(field_name)
+ if existing is None:
client.create_payload_index(
collection_name=name,
field_name=field_name,
field_schema=field_schema,
- )
\ No newline at end of file
+ )
+ continue
+
+ existing_schema = getattr(existing, "data_type", None)
+ if existing_schema != field_schema:
+ raise ValueError(
+ f"Payload index for '{field_name}' has schema "
+ f"{existing_schema!r}, expected {field_schema!r}."
+ )
+
+
+def scroll_all(
+ collection_name: str,
+ scroll_filter: qmodels.Filter | None = None,
+ with_payload: bool | list[str] = True,
+ limit: int = _SCROLL_PAGE_SIZE,
+) -> Iterator[list[qmodels.Record]]:
+ """Yield pages of Qdrant points (no vectors) until the collection is exhausted."""
+ client = get_client()
+ offset = None
+ while True:
+ try:
+ points, next_offset = client.scroll(
+ collection_name=collection_name,
+ scroll_filter=scroll_filter,
+ limit=limit,
+ offset=offset,
+ with_payload=with_payload,
+ with_vectors=False,
+ )
+ except ValueError as exc:
+ # Local Qdrant raises ValueError when collection doesn't exist yet.
+ if "not found" in str(exc).lower():
+ return
+ raise
+ yield points
+ if next_offset is None:
+ break
+ offset = next_offset
+
+
+def get_vector_store(collection_name: str | None = None) -> QdrantVectorStore:
+ return QdrantVectorStore(
+ client=get_client(),
+ collection_name=collection_name or settings.qdrant_collection,
+ embedding=get_embeddings(),
+ )
+
+
+def list_documents() -> list[dict[str, object]]:
+ """List indexed documents with filename, document_id, pages, and chunk counts.
+
+ Returns one entry per filename matching the API `DocumentInfo` shape.
+ """
+ pages_map: dict[str, set[int]] = {}
+ doc_id_map: dict[str, str] = {}
+ count_map: dict[str, int] = {}
+
+ for batch in scroll_all(settings.qdrant_collection, with_payload=["metadata"]):
+ for point in batch:
+ meta = (point.payload or {}).get("metadata") or {}
+ filename = meta.get("filename")
+ document_id = meta.get("document_id")
+ pg = meta.get("page")
+ if not filename or not document_id or not isinstance(pg, int):
+ continue
+ fn = str(filename)
+ doc_id_map.setdefault(fn, str(document_id))
+ pages_map.setdefault(fn, set()).add(pg)
+ count_map[fn] = count_map.get(fn, 0) + 1
+
+ return sorted(
+ [
+ {
+ "filename": fn,
+ "document_id": doc_id_map[fn],
+ "pages": sorted(pages_map[fn]),
+ "page_count": len(pages_map[fn]),
+ "chunk_count": count_map[fn],
+ }
+ for fn in doc_id_map
+ ],
+ key=lambda d: str(d["filename"]),
+ )
diff --git a/src/ui/__init__.py b/src/ui/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9352742b0b1ccab17830613245827ae7ff08f6f7
--- /dev/null
+++ b/src/ui/__init__.py
@@ -0,0 +1,4 @@
+from src.ui.layout import build_demo
+from src.ui.runtime import launch_demo
+
+__all__ = ["build_demo", "launch_demo"]
diff --git a/src/ui/callbacks.py b/src/ui/callbacks.py
new file mode 100644
index 0000000000000000000000000000000000000000..75a3a9bfb38263ae73a7007c7510a1da445e2f41
--- /dev/null
+++ b/src/ui/callbacks.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+import json
+
+import gradio as gr
+
+from src.export import export
+from src.learning import generate_flashcards, generate_quiz, summarize
+from src.llm import set_runtime_gemini_api_key
+from src.rag import answer
+from src.ui.helpers import PROGRESS
+from src.ui.uploads import build_filters
+
+
+def ask_question(
+ question: str,
+ k: int,
+ selected_docs: list[str],
+ page: str,
+ gemini_key: str,
+) -> tuple[str, str]:
+ if not question or not question.strip():
+ return "Vui lòng nhập câu hỏi.", ""
+ page_num = None if page == "(Tất cả trang)" else int(page)
+ set_runtime_gemini_api_key(gemini_key)
+ result = answer(
+ question.strip(),
+ k=int(k),
+ filters=build_filters(selected_docs, page_num),
+ )
+ return (
+ str(export(result, fmt="md")),
+ json.dumps(result.model_dump(), ensure_ascii=False, indent=2),
+ )
+
+
+def ask_chat(
+ message: str,
+ history: list[dict[str, str]] | None,
+ k: int,
+ selected_docs: list[str],
+ page: str,
+ gemini_key: str,
+) -> tuple[list[dict[str, str]], str, str]:
+ user_text = (message or "").strip()
+ turns = list(history or [])
+ if not user_text:
+ return turns, "", ""
+ answer_md, raw = ask_question(user_text, k, selected_docs, page, gemini_key)
+ turns.append({"role": "user", "content": user_text})
+ turns.append({"role": "assistant", "content": answer_md})
+ return turns, raw, ""
+
+
+def summarize_documents(
+ query: str,
+ k: int,
+ selected_docs: list[str],
+ page: str,
+ gemini_key: str,
+ progress: gr.Progress = PROGRESS,
+) -> tuple[str, str]:
+ page_num = None if page == "(Tất cả trang)" else int(page)
+ set_runtime_gemini_api_key(gemini_key)
+ progress(0.3, desc="Đang truy xuất ngữ cảnh…")
+ try:
+ result = summarize(
+ query=query.strip() or None,
+ k=int(k),
+ filters=build_filters(selected_docs, page_num),
+ )
+ except RuntimeError as error:
+ raise _empty_result_error() from error
+ progress(0.9, desc="Đang định dạng kết quả…")
+ return str(export(result, fmt="md")), result.model_dump_json(indent=2)
+
+
+def generate_quiz_set(
+ query: str,
+ count: int,
+ k: int,
+ selected_docs: list[str],
+ page: str,
+ gemini_key: str,
+ progress: gr.Progress = PROGRESS,
+) -> tuple[str, str]:
+ page_num = None if page == "(Tất cả trang)" else int(page)
+ set_runtime_gemini_api_key(gemini_key)
+ progress(0.3, desc="Đang truy xuất ngữ cảnh…")
+ try:
+ result = generate_quiz(
+ query=query.strip() or None,
+ count=int(count),
+ k=int(k),
+ filters=build_filters(selected_docs, page_num),
+ )
+ except RuntimeError as error:
+ raise _empty_result_error() from error
+ progress(0.9, desc="Đang định dạng kết quả…")
+ return str(export(result, fmt="md")), result.model_dump_json(indent=2)
+
+
+def generate_flashcard_set(
+ query: str,
+ count: int,
+ k: int,
+ selected_docs: list[str],
+ page: str,
+ gemini_key: str,
+ progress: gr.Progress = PROGRESS,
+) -> tuple[str, str]:
+ page_num = None if page == "(Tất cả trang)" else int(page)
+ set_runtime_gemini_api_key(gemini_key)
+ progress(0.3, desc="Đang truy xuất ngữ cảnh…")
+ try:
+ result = generate_flashcards(
+ query=query.strip() or None,
+ count=int(count),
+ k=int(k),
+ filters=build_filters(selected_docs, page_num),
+ )
+ except RuntimeError as error:
+ raise _empty_result_error() from error
+ progress(0.9, desc="Đang định dạng kết quả…")
+ return str(export(result, fmt="md")), result.model_dump_json(indent=2)
+
+
+def _empty_result_error() -> gr.Error:
+ return gr.Error(
+ "Chưa có nội dung phù hợp để tạo kết quả. Hãy nạp tài liệu, chọn phạm vi rồi thử lại."
+ )
diff --git a/src/ui/content.py b/src/ui/content.py
new file mode 100644
index 0000000000000000000000000000000000000000..f24d83f0a93459fc83a6c9116f10adba7277dffe
--- /dev/null
+++ b/src/ui/content.py
@@ -0,0 +1,98 @@
+BRAND_HEADER_HTML = """
+
+
+
+
+
+ DocuLearn-RAG
+
+
+
+ Local-first workspace
+
+
+
+
+
Document intelligence workspace
+
Học sâu hơn từ tài liệu của bạn.
+
Biến PDF thành một không gian học có dẫn nguồn — hỏi đáp, tóm tắt,
+ quiz và flashcards trên cùng một luồng làm việc.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+"""
+
+INFO_NOTE_HTML = """
+
+
+ Bắt đầu
+ Một luồng học, bốn công cụ.
+
+
+
01Tải PDF
+
02Chọn phạm vi
+
03Nhập Gemini key
+
04Bắt đầu học
+
+
+"""
+
+UPLOAD_HEADING_HTML = """
+
+
+
+
+
Nguồn tài liệu
Tải và lập chỉ mục PDF của bạn.
+
+"""
+
+LIBRARY_HEADING_HTML = """
+
+
+
+
+
Thư viện đã index
Chọn tài liệu và phạm vi trước khi truy vấn.
+
+"""
+
+EMPTY_LIBRARY_HTML = """
+
+
+
+
+ Thư viện đang trống
+ Tải PDF ở khung bên trái để bắt đầu không gian học của bạn.
+