Thanh Quang commited on
Commit
6b8bb0d
·
1 Parent(s): 5d5e833

update api, ui

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.env.example CHANGED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Required for Q&A and learning generation. Never commit a real key.
2
+ GEMINI_API_KEY=
3
+
4
+ # Optional API protection. Clients then send the X-API-Key header.
5
+ RAG_API_KEY=
6
+
7
+ # Optional Gradio basic authentication; configure both or neither.
8
+ RAG_GRADIO_USERNAME=
9
+ RAG_GRADIO_PASSWORD=
10
+
11
+ # Runtime paths and limits.
12
+ RAG_DATA_DIR=data
13
+ RAG_STORAGE_DIR=storage/qdrant
14
+ RAG_EXPORT_DIR=exports
15
+ RAG_MAX_UPLOAD_BYTES=26214400
16
+ RAG_SERVER_NAME=127.0.0.1
17
+ RAG_SERVER_PORT=7860
.gitignore CHANGED
@@ -10,8 +10,41 @@ wheels/
10
  .venv
11
 
12
  .env
 
 
 
 
 
 
 
13
 
14
  # General
15
  .DS_Store
16
  .AppleDouble
17
- .LSOverride
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  .venv
11
 
12
  .env
13
+ .pytest_cache/
14
+ .ruff_cache/
15
+ .coverage
16
+ htmlcov/
17
+ storage/
18
+ exports/
19
+ evaluation-results/
20
 
21
  # General
22
  .DS_Store
23
  .AppleDouble
24
+ .LSOverride
25
+ DESIGN.md
26
+ .omo/
27
+
28
+ # Notebook
29
+ .ipynb_checkpoints/
30
+
31
+ # Type-checker caches
32
+ .mypy_cache/
33
+ .pyright/
34
+ .basedpyright/
35
+
36
+ # Logs and temporary files
37
+ *.log
38
+ *.tmp
39
+ *.swp
40
+
41
+ # Coverage reports
42
+ coverage.xml
43
+ .coverage.*
44
+
45
+ # Gradio runtime artifacts
46
+ flagged/
47
+ gradio_cached_examples/
48
+
49
+ data/*.pdf
50
+ data/**/*.pdf
README.md CHANGED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DocuLearn-RAG
2
+
3
+ Ứ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à
4
+ flashcards có trích dẫn nguồn. Giao diện web dùng Gradio; dự án cũng cung cấp
5
+ CLI và REST API.
6
+
7
+ ## Cài đặt
8
+
9
+ Yêu cầu Python 3.12 và [uv](https://docs.astral.sh/uv/).
10
+
11
+ ```bash
12
+ uv sync --all-groups
13
+ cp .env.example .env
14
+ ```
15
+
16
+ Điền `GEMINI_API_KEY` trong `.env`, hoặc nhập key trực tiếp trong giao diện.
17
+ Không commit file `.env`.
18
+
19
+ ## Chạy ứng dụng
20
+
21
+ Gradio:
22
+
23
+ ```bash
24
+ uv run python app.py
25
+ ```
26
+
27
+ Mặc định giao diện chạy tại `http://127.0.0.1:7860`.
28
+
29
+ CLI:
30
+
31
+ ```bash
32
+ uv run doculearn-rag --help
33
+ uv run doculearn-rag ingest
34
+ uv run doculearn-rag ask "Nội dung chính của tài liệu là gì?"
35
+ uv run doculearn-rag summarize --document "example.pdf" --output exports/summary.md
36
+ ```
37
+
38
+ FastAPI:
39
+
40
+ ```bash
41
+ uv run uvicorn src.interfaces.api:app --host 127.0.0.1 --port 8000
42
+ ```
43
+
44
+ OpenAPI docs ở `http://127.0.0.1:8000/docs`. Nếu cấu hình `RAG_API_KEY`, gửi
45
+ header `X-API-Key` cho mọi route trừ `/health`.
46
+
47
+ ## Dữ liệu và cấu hình
48
+
49
+ - PDF đầu vào: `data/`
50
+ - Qdrant cục bộ: `storage/qdrant/`
51
+ - File Markdown tải từ UI: `exports/`
52
+ - Kích thước upload mặc định: 25 MiB
53
+
54
+ Các đường dẫn tương đối luôn được resolve theo thư mục gốc dự án, nên CLI/API
55
+ có thể chạy từ working directory khác.
56
+
57
+ ## Kiểm tra
58
+
59
+ ```bash
60
+ uv run pytest -q
61
+ uv run ruff check app.py src tests
62
+ uv run ruff format --check app.py src tests
63
+ uv run basedpyright --level error src
64
+ ```
65
+
66
+ ## Đánh giá chunking
67
+
68
+ File test JSON có dạng:
69
+
70
+ ```json
71
+ [
72
+ {
73
+ "question": "Câu hỏi cần đánh giá",
74
+ "ground_truth": "Câu trả lời tham chiếu"
75
+ }
76
+ ]
77
+ ```
78
+
79
+ Chạy:
80
+
81
+ ```bash
82
+ uv run python -m src.evaluation.run_chunking evaluation_cases.json
83
+ ```
84
+
85
+ Evaluation gọi Gemini và cần `GEMINI_API_KEY`. Dự án ghim Ragas `0.3.9` cùng
86
+ `langchain-community==0.3.31` vì Ragas `0.4.3` hiện import một module VertexAI
87
+ đã bị xóa ở dòng LangChain Community mới.
app.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from src.ui import build_demo, launch_demo
2
+
3
+ demo = build_demo()
4
+
5
+ if __name__ == "__main__":
6
+ launch_demo(demo)
assets/5_Q&A_RAG_Pipeline.png ADDED
assets/6_MapReduce_Strategy.png ADDED
data/[Data]-Benchmark-Rag.csv ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ no.,question,ground truth,
2
+ 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.",
3
+ 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.",
4
+ 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.,
5
+ 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ớ.,
6
+ 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.",
7
+ 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.,
8
+ 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 đó.,
9
+ 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.",
10
+ 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.,
11
+ 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.,
12
+ 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.,
13
+ 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ể.",
14
+ 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.",
15
+ 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,.",
16
+ 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).,
17
+ 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.,
18
+ 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.",
19
+ 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.,
20
+ 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.,
21
+ 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.,
22
+ 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.",
23
+ 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).",
24
+ 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.,
25
+ 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,.",
26
+ 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),.",
27
+ 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,.",
28
+ 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.,
29
+ 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.,
30
+ 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.,
31
+ 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.,
32
+ 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.,
33
+ 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ẻ <thinking> và </thinking>.,
34
+ 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ẻ <answer> và </answer>.,
35
+ 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,.",
36
+ 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.,
37
+ 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.,
38
+ 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.,
39
+ 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.,
40
+ 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.,
41
+ 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.,
42
+ 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.",
43
+ 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,.",
44
+ 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.,
45
+ 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.",
46
+ 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ữ.",
47
+ 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,.",
48
+ 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.",
49
+ 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.,
50
+ 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,.",
51
+ 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,.",
pyproject.toml CHANGED
@@ -1,21 +1,68 @@
1
  [project]
2
- name = "building-simple-notebooklm"
3
  version = "0.1.0"
4
- description = "Add your description here"
5
  readme = "README.md"
6
  requires-python = ">=3.12"
7
  dependencies = [
 
8
  "fastapi>=0.139.2",
9
- "langchain>=1.3.14",
10
- "langchain-community>=0.4.2",
 
11
  "langchain-google-genai>=4.3.1",
12
- "langchain-huggingface>=1.2.2",
13
- "langchain-openai>=1.4.0",
14
  "langchain-qdrant>=1.1.0",
15
- "pip>=26.1.2",
 
16
  "pydantic>=2.13.4",
 
17
  "pypdf>=6.14.2",
 
18
  "qdrant-client>=1.18.0",
19
- "torch>=2.13.0",
20
- "transformers>=5.14.1",
 
 
21
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  [project]
2
+ name = "doculearn-rag"
3
  version = "0.1.0"
4
+ description = "A local PDF-grounded learning assistant with Q&A, summaries, quizzes, and flashcards."
5
  readme = "README.md"
6
  requires-python = ">=3.12"
7
  dependencies = [
8
+ "datasets>=5.0.0",
9
  "fastapi>=0.139.2",
10
+ "google-genai>=1.0.0",
11
+ "gradio>=6.20.0",
12
+ "langchain-community==0.3.31",
13
  "langchain-google-genai>=4.3.1",
 
 
14
  "langchain-qdrant>=1.1.0",
15
+ "langchain-text-splitters>=1.0.0",
16
+ "loguru>=0.7.3",
17
  "pydantic>=2.13.4",
18
+ "pydantic-settings>=2.0.0",
19
  "pypdf>=6.14.2",
20
+ "python-multipart>=0.0.20",
21
  "qdrant-client>=1.18.0",
22
+ "ragas==0.3.9",
23
+ "sentence-transformers>=5.6.0",
24
+ "typer>=0.21.0",
25
+ "uvicorn>=0.42.0",
26
  ]
27
+
28
+ [project.scripts]
29
+ doculearn-rag = "src.interfaces.cli:app"
30
+ notebooklm = "src.interfaces.cli:app"
31
+
32
+ [build-system]
33
+ requires = ["setuptools>=80"]
34
+ build-backend = "setuptools.build_meta"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["."]
38
+ include = ["src*"]
39
+
40
+ [tool.setuptools]
41
+ py-modules = ["app"]
42
+
43
+ [tool.uv]
44
+ package = true
45
+
46
+ [dependency-groups]
47
+ dev = [
48
+ "basedpyright>=1.29.0",
49
+ "httpx>=0.28.0",
50
+ "pytest>=9.0.0",
51
+ "pytest-cov>=7.0.0",
52
+ "ruff>=0.14.0",
53
+ ]
54
+
55
+ [tool.pytest.ini_options]
56
+ testpaths = ["tests"]
57
+ addopts = ["-ra", "--strict-config", "--strict-markers"]
58
+
59
+ [tool.ruff]
60
+ target-version = "py312"
61
+ line-length = 100
62
+
63
+ [tool.ruff.lint]
64
+ select = ["E", "F", "I", "B", "UP"]
65
+
66
+ [tool.basedpyright]
67
+ include = ["src", "app.py"]
68
+ exclude = ["tests", ".venv", "data", "storage", "exports"]
requirements.txt → src/__init__.py RENAMED
File without changes
src/config.py CHANGED
@@ -1,75 +1,79 @@
 
 
1
  from functools import lru_cache
2
  from pathlib import Path
3
  from typing import Literal
4
 
5
- from pydantic import Field, model_validator
6
  from pydantic_settings import BaseSettings, SettingsConfigDict
7
 
 
 
8
 
9
  class Settings(BaseSettings):
10
  model_config = SettingsConfigDict(
11
- env_file=".env",
12
  env_prefix="RAG_",
13
  extra="ignore",
14
  )
15
 
16
- # Paths and vector database
17
  data_dir: Path = Path("data")
18
  storage_dir: Path = Path("storage/qdrant")
 
19
  qdrant_collection: str = "rag_chunks"
 
20
 
21
- # Chunking and retrieval
22
- chunk_size: int = Field(default=1000, ge=100)
23
- chunk_overlap: int = Field(default=150, ge=0)
24
  top_k: int = Field(default=5, ge=1, le=64)
25
 
26
- # Embedding and LLM
27
- embedding_model: str = (
28
- "GreenNode/GreenNode-Embedding-Large-VN-Mixed-V1"
29
- )
30
-
31
- llm_provider: Literal["hf_local", "gemini", "vllm"] = "hf_local"
32
  llm_temperature: float = Field(default=0.1, ge=0.0, le=2.0)
 
33
 
34
- # Hugging Face
35
- hf_device: Literal["mps", "cuda", "cpu"] = "mps"
36
- hf_max_new_tokens: int = Field(default=2048, ge=1)
37
-
38
- # Gemini
39
- gemini_model: str = "gemini-3.5-flash"
40
- google_api_key: str | None = Field(
41
- default=None,
42
- validation_alias="GOOGLE_API_KEY",
43
- )
44
 
45
- # vLLM
46
- vllm_api_base: str = "http://localhost:8001/v1"
47
- vllm_api_key: str = "EMPTY"
 
 
 
48
 
49
- # Summarization and generation
50
  summarize_batch_size: int = Field(default=10, ge=1)
51
  summarize_retrieval_k: int = Field(default=12, ge=1, le=128)
52
  generation_retrieval_k: int = Field(default=16, ge=1, le=128)
53
-
54
- # Learning materials
55
  quiz_default_count: int = Field(default=8, ge=1, le=50)
56
  flashcards_default_count: int = Field(default=15, ge=1, le=100)
57
 
58
- # API
59
- api_url: str = "http://localhost:8000"
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  @model_validator(mode="after")
62
- def validate_config(self) -> "Settings":
63
  if self.chunk_overlap >= self.chunk_size:
 
 
64
  raise ValueError(
65
- "chunk_overlap must be smaller than chunk_size."
66
- )
67
-
68
- if self.llm_provider == "gemini" and not self.google_api_key:
69
- raise ValueError(
70
- "GOOGLE_API_KEY is required when "
71
- "llm_provider='gemini'."
72
  )
 
 
 
 
73
 
74
  return self
75
 
@@ -79,4 +83,4 @@ def get_settings() -> Settings:
79
  return Settings()
80
 
81
 
82
- settings = get_settings()
 
1
+ from __future__ import annotations
2
+
3
  from functools import lru_cache
4
  from pathlib import Path
5
  from typing import Literal
6
 
7
+ from pydantic import Field, field_validator, model_validator
8
  from pydantic_settings import BaseSettings, SettingsConfigDict
9
 
10
+ _PROJECT_ROOT = Path(__file__).resolve().parents[1]
11
+
12
 
13
  class Settings(BaseSettings):
14
  model_config = SettingsConfigDict(
15
+ env_file=_PROJECT_ROOT / ".env",
16
  env_prefix="RAG_",
17
  extra="ignore",
18
  )
19
 
 
20
  data_dir: Path = Path("data")
21
  storage_dir: Path = Path("storage/qdrant")
22
+ export_dir: Path = Path("exports")
23
  qdrant_collection: str = "rag_chunks"
24
+ max_upload_bytes: int = Field(default=25 * 1024 * 1024, ge=1024)
25
 
26
+ chunk_size: int = Field(default=1500, ge=500)
27
+ chunk_overlap: int = Field(default=200, ge=0)
 
28
  top_k: int = Field(default=5, ge=1, le=64)
29
 
30
+ llm_provider: Literal["gemini"] = "gemini"
31
+ llm_model: str = "gemini-flash-lite-latest"
 
 
 
 
32
  llm_temperature: float = Field(default=0.1, ge=0.0, le=2.0)
33
+ llm_max_new_tokens: int = Field(default=10000, ge=1, le=20000)
34
 
35
+ embedding_provider: Literal["local"] = "local"
36
+ embedding_model: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
 
 
 
 
 
 
 
 
37
 
38
+ gemini_api_key: str | None = Field(default=None, validation_alias="GEMINI_API_KEY")
39
+ api_key: str | None = None
40
+ gradio_username: str | None = None
41
+ gradio_password: str | None = None
42
+ server_name: str = "127.0.0.1"
43
+ server_port: int = Field(default=7860, ge=1, le=65535)
44
 
 
45
  summarize_batch_size: int = Field(default=10, ge=1)
46
  summarize_retrieval_k: int = Field(default=12, ge=1, le=128)
47
  generation_retrieval_k: int = Field(default=16, ge=1, le=128)
 
 
48
  quiz_default_count: int = Field(default=8, ge=1, le=50)
49
  flashcards_default_count: int = Field(default=15, ge=1, le=100)
50
 
51
+ @field_validator(
52
+ "gemini_api_key",
53
+ "api_key",
54
+ "gradio_username",
55
+ "gradio_password",
56
+ mode="before",
57
+ )
58
+ @classmethod
59
+ def normalize_blank_secrets(cls, value: object) -> object:
60
+ """Treat blank optional credentials as disabled configuration."""
61
+ if isinstance(value, str) and not value.strip():
62
+ return None
63
+ return value
64
 
65
  @model_validator(mode="after")
66
+ def validate_config(self) -> Settings:
67
  if self.chunk_overlap >= self.chunk_size:
68
+ raise ValueError("chunk_overlap must be smaller than chunk_size.")
69
+ if bool(self.gradio_username) != bool(self.gradio_password):
70
  raise ValueError(
71
+ "RAG_GRADIO_USERNAME and RAG_GRADIO_PASSWORD must be configured together."
 
 
 
 
 
 
72
  )
73
+ for field_name in ("data_dir", "storage_dir", "export_dir"):
74
+ path = getattr(self, field_name)
75
+ if not path.is_absolute():
76
+ object.__setattr__(self, field_name, _PROJECT_ROOT / path)
77
 
78
  return self
79
 
 
83
  return Settings()
84
 
85
 
86
+ settings = get_settings()
src/embeddings.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local embeddings via Sentence-Transformers (no inference provider)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+ from typing import cast
7
+
8
+ from langchain_core.embeddings import Embeddings
9
+ from sentence_transformers import SentenceTransformer
10
+
11
+ from src.config import settings
12
+
13
+
14
+ @lru_cache(maxsize=1)
15
+ def _model() -> SentenceTransformer:
16
+ return SentenceTransformer(settings.embedding_model)
17
+
18
+
19
+ class LocalSentenceTransformerEmbeddings(Embeddings):
20
+ def embed_documents(self, texts: list[str]) -> list[list[float]]: # type: ignore[override]
21
+ vecs = _model().encode(texts, normalize_embeddings=True)
22
+ tolist = getattr(vecs, "tolist", None)
23
+ if callable(tolist):
24
+ return cast(list[list[float]], tolist())
25
+ return [list(map(float, v)) for v in vecs]
26
+
27
+ def embed_query(self, text: str) -> list[float]: # type: ignore[override]
28
+ vec = _model().encode([text], normalize_embeddings=True)[0]
29
+ tolist = getattr(vec, "tolist", None)
30
+ if callable(tolist):
31
+ return cast(list[float], tolist())
32
+ return [float(x) for x in vec]
33
+
34
+
35
+ def get_embeddings() -> Embeddings:
36
+ return LocalSentenceTransformerEmbeddings()
src/evaluation/README.md CHANGED
@@ -1,3 +1,9 @@
1
- RAG Evaluation
2
 
3
- The src/evaluation/ directory contains components for evaluating the quality and performance of the RAG system.
 
 
 
 
 
 
 
1
+ # RAG evaluation
2
 
3
+ `chunking_strategy.py` defines the pre-registered recursive chunking grid.
4
+ `ragas_evaluator.py` converts DocuLearn-RAG answers into a Ragas dataset.
5
+ `run_chunking.py` rebuilds one isolated Qdrant collection per strategy and
6
+ writes mean metric values to `evaluation-results/chunking/`.
7
+
8
+ Evaluation uses the configured local embedding model and Gemini as judge, so
9
+ it requires `GEMINI_API_KEY` and may incur API usage.
src/evaluation/chunking_strategies.py DELETED
File without changes
src/evaluation/chunking_strategy.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reusable chunking strategies for controlled retrieval experiments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from langchain_core.documents import Document
8
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
9
+
10
+ from src.indexing import Chunker
11
+
12
+ DEFAULT_SEPARATORS = ("\n\n", "\n", ". ", " ", "")
13
+ RECURSIVE_CONFIGS = (
14
+ ("rc_500_50", 500, 50),
15
+ ("rc_800_100", 800, 100),
16
+ ("rc_1000_150", 1000, 150),
17
+ ("rc_1500_200", 1500, 200),
18
+ )
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class RecursiveChunker:
23
+ chunk_size: int = 500
24
+ chunk_overlap: int = 50
25
+ separators: tuple[str, ...] = DEFAULT_SEPARATORS
26
+
27
+ def __post_init__(self) -> None:
28
+ if self.chunk_size <= 0:
29
+ raise ValueError("chunk_size must be positive.")
30
+ if not 0 <= self.chunk_overlap < self.chunk_size:
31
+ raise ValueError("chunk_overlap must be non-negative and smaller than chunk_size.")
32
+
33
+ def split_documents(self, documents: list[Document]) -> list[Document]:
34
+ if not documents:
35
+ return []
36
+ splitter = RecursiveCharacterTextSplitter(
37
+ chunk_size=self.chunk_size,
38
+ chunk_overlap=self.chunk_overlap,
39
+ separators=list(self.separators),
40
+ is_separator_regex=False,
41
+ )
42
+ return splitter.split_documents(documents)
43
+
44
+
45
+ @dataclass(frozen=True, slots=True)
46
+ class ChunkingStrategy:
47
+ strategy_id: str
48
+ chunker: Chunker
49
+ params: dict[str, int]
50
+
51
+
52
+ def recursive_strategies() -> list[ChunkingStrategy]:
53
+ """Build the pre-registered recursive chunking strategy grid."""
54
+ return [
55
+ ChunkingStrategy(
56
+ strategy_id=strategy_id,
57
+ chunker=RecursiveChunker(chunk_size=chunk_size, chunk_overlap=chunk_overlap),
58
+ params={"chunk_size": chunk_size, "chunk_overlap": chunk_overlap},
59
+ )
60
+ for strategy_id, chunk_size, chunk_overlap in RECURSIVE_CONFIGS
61
+ ]
src/evaluation/ragas_evaluator.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ragas evaluation adapter for grounded DocuLearn-RAG answers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import TypedDict
7
+
8
+ from datasets import Dataset
9
+ from langchain_google_genai import ChatGoogleGenerativeAI
10
+
11
+ from src.config import settings
12
+ from src.embeddings import get_embeddings
13
+ from src.rag import answer as default_answer_fn
14
+ from src.schemas import RagAnswer
15
+
16
+
17
+ class EvaluationCase(TypedDict):
18
+ question: str
19
+ ground_truth: str
20
+
21
+
22
+ def _evaluation_dataset(
23
+ test_cases: list[EvaluationCase],
24
+ answer_fn: Callable[[str], RagAnswer],
25
+ ) -> Dataset:
26
+ if not test_cases:
27
+ raise ValueError("test_cases cannot be empty.")
28
+
29
+ data: dict[str, list[object]] = {
30
+ "question": [],
31
+ "answer": [],
32
+ "contexts": [],
33
+ "ground_truth": [],
34
+ }
35
+ for index, case in enumerate(test_cases):
36
+ question = case.get("question", "").strip()
37
+ ground_truth = case.get("ground_truth", "").strip()
38
+ if not question or not ground_truth:
39
+ raise ValueError(
40
+ "Each test case must contain non-empty 'question' and "
41
+ f"'ground_truth' values (index {index})."
42
+ )
43
+ rag_response = answer_fn(question)
44
+ data["question"].append(question)
45
+ data["answer"].append(rag_response.answer)
46
+ data["contexts"].append([chunk.text for chunk in rag_response.chunks])
47
+ data["ground_truth"].append(ground_truth)
48
+ return Dataset.from_dict(data)
49
+
50
+
51
+ def run_evaluation(
52
+ test_cases: list[EvaluationCase],
53
+ *,
54
+ answer_fn: Callable[[str], RagAnswer] = default_answer_fn,
55
+ timeout_s: int = 180,
56
+ max_retries: int = 3,
57
+ max_workers: int = 4,
58
+ ):
59
+ """Evaluate grounded answers with Ragas 0.3's stable LangChain adapter."""
60
+ if not settings.gemini_api_key:
61
+ raise RuntimeError("GEMINI_API_KEY is required for Ragas evaluation.")
62
+
63
+ from ragas import evaluate
64
+ from ragas.embeddings import LangchainEmbeddingsWrapper
65
+ from ragas.llms import LangchainLLMWrapper
66
+ from ragas.metrics import answer_relevancy, context_precision, context_recall, faithfulness
67
+ from ragas.run_config import RunConfig
68
+
69
+ dataset = _evaluation_dataset(test_cases, answer_fn)
70
+ llm = LangchainLLMWrapper(
71
+ ChatGoogleGenerativeAI(
72
+ model=settings.llm_model,
73
+ google_api_key=settings.gemini_api_key,
74
+ temperature=settings.llm_temperature,
75
+ )
76
+ )
77
+ embeddings = LangchainEmbeddingsWrapper(get_embeddings())
78
+ metrics = [faithfulness, answer_relevancy, context_precision, context_recall]
79
+ return evaluate(
80
+ dataset=dataset,
81
+ metrics=metrics,
82
+ llm=llm,
83
+ embeddings=embeddings,
84
+ run_config=RunConfig(
85
+ timeout=timeout_s,
86
+ max_retries=max_retries,
87
+ max_workers=max_workers,
88
+ ),
89
+ )
src/evaluation/run_chunking.py CHANGED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the registered chunking grid against a JSON evaluation set."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any, cast
9
+
10
+ from src.config import settings
11
+ from src.evaluation.chunking_strategy import recursive_strategies
12
+ from src.evaluation.ragas_evaluator import EvaluationCase, run_evaluation
13
+ from src.indexing import ingest
14
+ from src.rag import answer
15
+ from src.schemas import RagAnswer
16
+
17
+
18
+ def _answer_for_collection(collection_name: str):
19
+ def answer_with_strategy(question: str) -> RagAnswer:
20
+ return answer(question, collection_name=collection_name)
21
+
22
+ return answer_with_strategy
23
+
24
+
25
+ def _load_cases(path: Path) -> list[EvaluationCase]:
26
+ payload = json.loads(path.read_text(encoding="utf-8"))
27
+ if not isinstance(payload, list):
28
+ raise ValueError("Evaluation file must contain a JSON list.")
29
+
30
+ cases: list[EvaluationCase] = []
31
+ for index, item in enumerate(payload):
32
+ if not isinstance(item, dict):
33
+ raise ValueError(f"Evaluation case {index} must be an object.")
34
+ question = item.get("question")
35
+ ground_truth = item.get("ground_truth")
36
+ if not isinstance(question, str) or not isinstance(ground_truth, str):
37
+ raise ValueError(
38
+ f"Evaluation case {index} requires string question and ground_truth fields."
39
+ )
40
+ cases.append({"question": question, "ground_truth": ground_truth})
41
+ return cases
42
+
43
+
44
+ def run(test_cases_path: Path, output_dir: Path) -> list[dict[str, object]]:
45
+ cases = _load_cases(test_cases_path)
46
+ output_dir.mkdir(parents=True, exist_ok=True)
47
+ reports: list[dict[str, object]] = []
48
+
49
+ for strategy in recursive_strategies():
50
+ collection_name = f"{settings.qdrant_collection}__{strategy.strategy_id}"
51
+ chunk_count = ingest(
52
+ recreate=True,
53
+ collection_name=collection_name,
54
+ chunker=strategy.chunker,
55
+ )
56
+
57
+ evaluation = run_evaluation(
58
+ cases,
59
+ answer_fn=_answer_for_collection(collection_name),
60
+ )
61
+ frame = cast(Any, evaluation).to_pandas()
62
+ numeric = frame.select_dtypes(include="number")
63
+ metrics = {
64
+ str(column): float(value) for column, value in numeric.mean(numeric_only=True).items()
65
+ }
66
+ report: dict[str, object] = {
67
+ "strategy_id": strategy.strategy_id,
68
+ "params": strategy.params,
69
+ "chunk_count": chunk_count,
70
+ "metrics": metrics,
71
+ }
72
+ (output_dir / f"{strategy.strategy_id}.json").write_text(
73
+ json.dumps(report, ensure_ascii=False, indent=2) + "\n",
74
+ encoding="utf-8",
75
+ )
76
+ reports.append(report)
77
+
78
+ return reports
79
+
80
+
81
+ def main() -> None:
82
+ parser = argparse.ArgumentParser(description=__doc__)
83
+ parser.add_argument("test_cases", type=Path)
84
+ parser.add_argument("--output-dir", type=Path, default=Path("evaluation-results/chunking"))
85
+ args = parser.parse_args()
86
+ reports = run(
87
+ cast(Path, args.test_cases),
88
+ cast(Path, args.output_dir),
89
+ )
90
+ print(json.dumps(reports, ensure_ascii=False, indent=2))
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
src/evaluation/run_reranking.py DELETED
File without changes
src/export.py CHANGED
@@ -1 +1,190 @@
1
- @lru_cache(maxsize=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export learning outputs to JSON or Markdown."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ from pydantic import BaseModel
11
+
12
+ from src.schemas import Citation, FlashcardSet, QuizSet, RagAnswer, Summary
13
+
14
+ ExportFormat = Literal["text", "md", "json"]
15
+ _ACTIVE_URI_SCHEME = re.compile(r"\b(?:https?|ftp|javascript|data):", re.IGNORECASE)
16
+
17
+
18
+ def _safe(value: str) -> str:
19
+ """Keep untrusted text readable without retaining active Markdown links."""
20
+ escaped = html.escape(value, quote=False).replace("[", r"\[").replace("]", r"\]")
21
+ return _ACTIVE_URI_SCHEME.sub(lambda match: match.group(0)[:-1] + r"\:", escaped)
22
+
23
+
24
+ def _safe_inline(value: str) -> str:
25
+ """Keep untrusted metadata on one inert Markdown line."""
26
+ return _safe(" ".join(value.splitlines())).replace("`", r"\`")
27
+
28
+
29
+ def safe_markdown_code(value: str) -> str:
30
+ """Render untrusted single-line metadata as an inert Markdown code span."""
31
+ normalized = html.escape(" ".join(value.splitlines()), quote=False)
32
+ normalized = _ACTIVE_URI_SCHEME.sub(
33
+ lambda match: match.group(0)[:-1] + r"\:",
34
+ normalized,
35
+ )
36
+ longest_run = max((len(run) for run in re.findall(r"`+", normalized)), default=0)
37
+ fence = "`" * (longest_run + 1)
38
+ padding = " " if normalized.startswith("`") or normalized.endswith("`") else ""
39
+ return f"{fence}{padding}{normalized}{padding}{fence}"
40
+
41
+
42
+ def _citation_line(c: Citation) -> str:
43
+ parts = [f"[{c.source_marker}] {_safe_inline(c.filename)} p.{c.page}"]
44
+ if c.section:
45
+ parts.append(f"section: {_safe_inline(c.section)}")
46
+ if c.chunk_id:
47
+ parts.append(f"chunk: {_safe_inline(c.chunk_id)}")
48
+ return " | ".join(parts)
49
+
50
+
51
+ def _details_block(summary: str, content: str) -> str:
52
+ safe_summary = html.escape(summary, quote=False)
53
+ safe_content = html.escape(content, quote=False)
54
+ return (
55
+ "<details>"
56
+ f"<summary>{safe_summary}</summary>"
57
+ f'<div style="margin:8px 0 0 0; white-space:pre-wrap;">{safe_content}</div>'
58
+ "</details>"
59
+ )
60
+
61
+
62
+ def _citation_source_text_block(c: Citation) -> str:
63
+ if not c.source_text:
64
+ return ""
65
+ return "\n " + _details_block("Xem đoạn nguồn", c.source_text)
66
+
67
+
68
+ def _marker_details(citations: list[Citation], markers: list[str]) -> list[str]:
69
+ by_marker = {c.source_marker: c for c in citations}
70
+ lines: list[str] = []
71
+ for m in markers:
72
+ c = by_marker.get(m)
73
+ if c is None:
74
+ continue
75
+ summary = f"[{c.source_marker}] {_safe_inline(c.filename)} p.{c.page}"
76
+ if c.section:
77
+ summary += f" | section: {_safe_inline(c.section)}"
78
+ if c.chunk_id:
79
+ summary += f" | chunk: {_safe_inline(c.chunk_id)}"
80
+ if c.source_text:
81
+ lines.append(f"- {_details_block(summary, c.source_text)}")
82
+ else:
83
+ lines.append(f"- {summary}")
84
+ return lines
85
+
86
+
87
+ def _citations_block(citations: list[Citation]) -> str:
88
+ if not citations:
89
+ return ""
90
+ lines = ["## Sources", ""]
91
+ for c in citations:
92
+ lines.append(f"- {_citation_line(c)}{_citation_source_text_block(c)}")
93
+ return "\n".join(lines) + "\n"
94
+
95
+
96
+ def _render_with_sources(body_lines: list[str], citations: list[Citation]) -> str:
97
+ lines = [*body_lines, ""]
98
+ c = _citations_block(citations)
99
+ if c:
100
+ lines.append(c)
101
+ return "\n".join(lines).rstrip() + "\n"
102
+
103
+
104
+ def _to_markdown(model: BaseModel) -> str:
105
+ if isinstance(model, Summary):
106
+ title = "# Summary" + (f": {_safe_inline(model.target)}" if model.target else "")
107
+ lines: list[str] = [title, "", f"_Scope: {model.scope}_", ""]
108
+ if model.summary:
109
+ lines.extend([_safe(model.summary.strip()), ""])
110
+ if model.key_points:
111
+ lines.extend(["## Key Points", "", *[f"- {_safe(kp)}" for kp in model.key_points], ""])
112
+ return _render_with_sources(lines, model.citations)
113
+
114
+ if isinstance(model, RagAnswer):
115
+ return _render_with_sources([_safe(model.answer.strip())], model.citations)
116
+
117
+ if isinstance(model, QuizSet):
118
+ title = "# Quiz" + (f": {_safe_inline(model.target)}" if model.target else "")
119
+ lines = [title, "", f"_Scope: {model.scope} | Items: {len(model.items)}_", ""]
120
+ for idx, item in enumerate(model.items, start=1):
121
+ meta_parts: list[str] = []
122
+ if item.topic:
123
+ meta_parts.append(f"topic: {_safe_inline(item.topic)}")
124
+ if item.difficulty:
125
+ meta_parts.append(f"difficulty: {_safe_inline(item.difficulty)}")
126
+ meta_suffix = f" _({' | '.join(meta_parts)})_" if meta_parts else ""
127
+
128
+ lines.extend([f"## Q{idx}.{meta_suffix}", "", _safe(item.question.strip()), ""])
129
+ for opt_idx, option in enumerate(item.options):
130
+ lines.append(f"- {chr(ord('A') + opt_idx)}) {_safe(option)}")
131
+ lines.append("")
132
+ lines.append(f"**Answer:** {chr(ord('A') + item.correct_index)}")
133
+ if item.explanation:
134
+ lines.append(f"**Explanation:** {_safe(item.explanation.strip())}")
135
+ if item.source_markers:
136
+ lines.extend(
137
+ ["**Sources:**", *_marker_details(model.citations, item.source_markers)]
138
+ )
139
+ lines.append("")
140
+
141
+ c = _citations_block(model.citations)
142
+ if c:
143
+ lines.append(c)
144
+ return "\n".join(lines).rstrip() + "\n"
145
+
146
+ if isinstance(model, FlashcardSet):
147
+ title = "# Flashcards" + (f": {_safe_inline(model.target)}" if model.target else "")
148
+ lines = [title, "", f"_Scope: {model.scope} | Cards: {len(model.cards)}_", ""]
149
+ for idx, card in enumerate(model.cards, start=1):
150
+ topic = f" — {_safe_inline(card.topic)}" if card.topic else ""
151
+ lines.extend([f"## Card {idx}{topic}", ""])
152
+ lines.append(f"**Front:** {_safe(card.front.strip())}")
153
+ lines.append(f"**Back:** {_safe(card.back.strip())}")
154
+ if card.hint:
155
+ lines.append(f"**Hint:** {_safe(card.hint.strip())}")
156
+ if card.source_markers:
157
+ lines.extend(
158
+ ["**Sources:**", *_marker_details(model.citations, card.source_markers)]
159
+ )
160
+ lines.append("")
161
+
162
+ c = _citations_block(model.citations)
163
+ if c:
164
+ lines.append(c)
165
+ return "\n".join(lines).rstrip() + "\n"
166
+
167
+ raise TypeError(f"Unsupported model type: {type(model).__name__}")
168
+
169
+
170
+ def export(
171
+ model: BaseModel, *, fmt: ExportFormat = "text", output: Path | None = None
172
+ ) -> str | Path:
173
+ """Render model to a string, optionally writing it to disk.
174
+ Args: model, fmt, output (optional).
175
+ Returns: rendered string if output is None; otherwise the written path.
176
+ Raises: TypeError for unsupported model type; ValueError for unknown fmt.
177
+ """
178
+ if fmt == "json":
179
+ text = model.model_dump_json(indent=2) + "\n"
180
+ elif fmt in {"text", "md"}:
181
+ text = _to_markdown(model)
182
+ else:
183
+ raise ValueError(f"Unknown fmt '{fmt}'. Expected 'text' | 'md' | 'json'.")
184
+
185
+ if output is None:
186
+ return text
187
+
188
+ output.parent.mkdir(parents=True, exist_ok=True)
189
+ output.write_text(text, encoding="utf-8")
190
+ return output
src/filters.py CHANGED
@@ -1,120 +1,87 @@
1
- from typing import Any
2
 
3
- from pydantic import BaseModel, field_validator, model_validator
4
- from qdrant_client import models as qmodels
 
 
5
 
6
 
7
  class MetadataFilter(BaseModel):
 
 
 
 
8
  filename: str | None = None
9
  filenames: list[str] | None = None
10
- page: int | None = None
11
  section: str | None = None
12
  document_id: str | None = None
13
 
14
- @field_validator("page")
15
- @classmethod
16
- def validate_page(cls, value: int | None) -> int | None:
17
- if value is not None and value < 1:
18
- raise ValueError("page must be greater than or equal to 1.")
19
-
20
- return value
21
-
22
  @model_validator(mode="after")
23
- def normalize(self) -> "MetadataFilter":
24
- # Chuẩn hóa filename đơn.
25
- if self.filename is not None:
26
- self.filename = self.filename.strip() or None
27
-
28
- # Chuẩn hóa danh sách filename.
29
- normalized_names = [
30
- name.strip()
31
- for name in (self.filenames or [])
32
- if isinstance(name, str) and name.strip()
33
- ]
34
-
35
- # Loại bỏ tên trùng nhưng vẫn giữ nguyên thứ tự.
36
- normalized_names = list(dict.fromkeys(normalized_names))
37
-
38
- # Nếu cả filename và filenames cùng được cung cấp,
39
- # đưa tất cả về filenames.
40
- if self.filename is not None:
41
- normalized_names.insert(0, self.filename)
42
- normalized_names = list(dict.fromkeys(normalized_names))
43
-
44
- if not normalized_names:
45
- self.filename = None
46
- self.filenames = None
47
- elif len(normalized_names) == 1:
48
- self.filename = normalized_names[0]
49
  self.filenames = None
 
 
50
  else:
51
- self.filename = None
52
- self.filenames = normalized_names
53
-
 
54
  if self.section is not None:
55
  self.section = self.section.strip() or None
56
-
57
  if self.document_id is not None:
58
  self.document_id = self.document_id.strip() or None
59
-
60
  return self
61
 
62
 
63
- def coerce_filter(
64
- filters: MetadataFilter | dict[str, Any] | None,
65
- ) -> MetadataFilter | None:
66
  if filters is None:
67
  return None
68
-
69
  if isinstance(filters, MetadataFilter):
70
  return filters
71
-
72
  if isinstance(filters, dict):
73
  return MetadataFilter.model_validate(filters)
 
74
 
75
- raise TypeError(
76
- "filters must be MetadataFilter, dict, or None."
77
- )
78
 
79
-
80
- def filters_to_dict(
81
- filters: MetadataFilter | dict[str, Any] | None,
82
- ) -> dict[str, Any] | None:
83
- normalized_filter = coerce_filter(filters)
84
-
85
- if normalized_filter is None:
86
  return None
87
-
88
- result = normalized_filter.model_dump(exclude_none=True)
89
-
90
- return result or None
91
 
92
 
93
- def filters_to_qdrant(
94
- filters: MetadataFilter | dict[str, Any] | None,
95
- ) -> qmodels.Filter | None:
96
- flat_filter = filters_to_dict(filters)
97
-
98
- if not flat_filter:
99
  return None
100
 
101
- conditions: list[qmodels.FieldCondition] = []
 
 
 
102
 
103
- for field_name, value in flat_filter.items():
104
- if field_name == "filenames":
105
- conditions.append(
106
- qmodels.FieldCondition(
107
- key="metadata.filename",
108
- match=qmodels.MatchAny(any=value),
 
109
  )
110
- )
111
  continue
112
 
113
- conditions.append(
114
- qmodels.FieldCondition(
115
- key=f"metadata.{field_name}",
116
- match=qmodels.MatchValue(value=value),
 
117
  )
118
- )
119
 
120
- return qmodels.Filter(must=conditions)
 
1
+ """Shared metadata filtering utilities across the app."""
2
 
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
6
+ from qdrant_client.http import models as qmodels
7
 
8
 
9
  class MetadataFilter(BaseModel):
10
+ """Filter applied against indexed chunk metadata."""
11
+
12
+ model_config = ConfigDict(extra="forbid")
13
+
14
  filename: str | None = None
15
  filenames: list[str] | None = None
16
+ page: int | None = Field(default=None, ge=1)
17
  section: str | None = None
18
  document_id: str | None = None
19
 
 
 
 
 
 
 
 
 
20
  @model_validator(mode="after")
21
+ def _normalize(self) -> MetadataFilter:
22
+ names = [x for x in (self.filenames or []) if isinstance(x, str) and x.strip()]
23
+ names = [n.strip() for n in names if n.strip()]
24
+ if not names:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  self.filenames = None
26
+ elif len(names) == 1:
27
+ self.filename, self.filenames = names[0], None
28
  else:
29
+ # Multi-doc selection: page filter becomes ambiguous, so drop it.
30
+ self.filename, self.filenames, self.page = None, names, None
31
+ if self.filename is not None:
32
+ self.filename = self.filename.strip() or None
33
  if self.section is not None:
34
  self.section = self.section.strip() or None
 
35
  if self.document_id is not None:
36
  self.document_id = self.document_id.strip() or None
 
37
  return self
38
 
39
 
40
+ def coerce_filter(filters: MetadataFilter | dict[str, object] | None) -> MetadataFilter | None:
41
+ """Coerce a dict (or None) into a normalized `MetadataFilter`."""
 
42
  if filters is None:
43
  return None
 
44
  if isinstance(filters, MetadataFilter):
45
  return filters
 
46
  if isinstance(filters, dict):
47
  return MetadataFilter.model_validate(filters)
48
+ raise TypeError(f"Unsupported filters type: {type(filters).__name__}")
49
 
 
 
 
50
 
51
+ def filters_to_dict(filters: MetadataFilter | dict[str, object] | None) -> dict[str, object] | None:
52
+ """Return normalized flat dict suitable for downstream filtering."""
53
+ f = coerce_filter(filters)
54
+ if f is None:
 
 
 
55
  return None
56
+ return f.model_dump(exclude_none=True) or None
 
 
 
57
 
58
 
59
+ def filters_to_qdrant(filters: MetadataFilter | dict[str, object] | None) -> qmodels.Filter | None:
60
+ """Build a Qdrant filter from normalized metadata filters."""
61
+ flat = filters_to_dict(filters)
62
+ if not flat:
 
 
63
  return None
64
 
65
+ conditions: list[qmodels.Condition] = []
66
+ for field, value in flat.items():
67
+ if value is None:
68
+ continue
69
 
70
+ if field == "filenames" and isinstance(value, list):
71
+ names = [x for x in value if isinstance(x, str) and x]
72
+ if names:
73
+ conditions.append(
74
+ qmodels.FieldCondition(
75
+ key="metadata.filename", match=qmodels.MatchAny(any=names)
76
+ )
77
  )
 
78
  continue
79
 
80
+ if isinstance(value, (str, int)):
81
+ conditions.append(
82
+ qmodels.FieldCondition(
83
+ key=f"metadata.{field}", match=qmodels.MatchValue(value=value)
84
+ )
85
  )
 
86
 
87
+ return qmodels.Filter(must=conditions) if conditions else None
src/indexing.py CHANGED
@@ -1,303 +1,244 @@
 
 
 
 
1
  import hashlib
 
 
2
  import uuid
3
  from collections import defaultdict
4
- from collections.abc import Iterable, Sequence
5
  from pathlib import Path
 
6
 
7
  from langchain_community.document_loaders import PyPDFLoader
8
  from langchain_core.documents import Document
9
  from langchain_text_splitters import RecursiveCharacterTextSplitter
 
10
 
11
- from config import settings
12
- from schemas import ChunkMetadata
13
- from store import ensure_collection, get_vector_store
14
-
15
 
16
- def _document_id(path: Path) -> str:
17
- hasher = hashlib.sha256()
18
- with path.open("rb") as file:
19
- for block in iter(lambda: file.read(1024 * 1024), b""):
20
- hasher.update(block)
21
 
22
- return hasher.hexdigest()[:16]
23
 
 
 
 
 
24
 
25
- def _chunk_id(
26
- document_id: str,
27
- page: int,
28
- index: int,
29
- ) -> str:
30
- return f"{document_id}:{page}:{index}"
31
 
 
 
 
 
 
32
 
33
- def discover_pdfs() -> list[Path]:
34
- """
35
- Tìm tất cả PDF trong thư mục dữ liệu.
36
- """
37
- settings.data_dir.mkdir(
38
- parents=True,
39
- exist_ok=True,
40
- )
41
-
42
- return sorted(
43
- path
44
- for path in settings.data_dir.rglob("*.pdf")
45
- if path.is_file()
46
  )
47
 
48
 
49
- def _load_pdf(path: Path) -> list[Document]:
50
- path = path.expanduser()
51
-
52
- if not path.exists():
53
- raise FileNotFoundError(
54
- f"PDF file not found: {path}"
55
- )
 
 
56
 
57
- if not path.is_file():
58
- raise ValueError(
59
- f"Path is not a file: {path}"
60
- )
61
 
62
- if path.suffix.lower() != ".pdf":
63
- raise ValueError(
64
- f"Expected a PDF file, received: {path.suffix}"
65
- )
66
 
67
- pages = PyPDFLoader(str(path)).load()
68
- document_id = _document_id(path)
69
-
70
- for document in pages:
71
- original_page = document.metadata.get("page", 0)
72
-
73
- try:
74
- page_number = int(original_page) + 1
75
- except (TypeError, ValueError) as error:
76
- raise ValueError(
77
- f"Invalid page metadata in PDF {path}: "
78
- f"{original_page!r}"
79
- ) from error
80
-
81
- document.metadata.update(
82
- {
83
- "document_id": document_id,
84
- "filename": path.name,
85
- "source": str(path.resolve()),
86
- "page": page_number,
87
- "section": document.metadata.get("section"),
88
- }
89
- )
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  return pages
92
 
93
 
94
- def _splitter(
95
- chunk_size: int | None = None,
96
- chunk_overlap: int | None = None,
97
- ) -> RecursiveCharacterTextSplitter:
98
- resolved_chunk_size = (
99
- settings.chunk_size
100
- if chunk_size is None
101
- else chunk_size
102
- )
103
-
104
- resolved_chunk_overlap = (
105
- settings.chunk_overlap
106
- if chunk_overlap is None
107
- else chunk_overlap
108
- )
109
-
110
- if resolved_chunk_size <= 0:
111
- raise ValueError(
112
- "chunk_size must be greater than 0."
113
- )
114
-
115
- if resolved_chunk_overlap < 0:
116
- raise ValueError(
117
- "chunk_overlap cannot be negative."
118
- )
119
-
120
- if resolved_chunk_overlap >= resolved_chunk_size:
121
- raise ValueError(
122
- "chunk_overlap must be smaller than chunk_size."
123
- )
124
-
125
- return RecursiveCharacterTextSplitter(
126
- chunk_size=resolved_chunk_size,
127
- chunk_overlap=resolved_chunk_overlap,
128
- separators=[
129
- "\n\n",
130
- "\n",
131
- ". ",
132
- " ",
133
- "",
134
- ],
135
- keep_separator=False,
136
- )
137
 
138
 
139
  def build_chunks(
140
- pdf_paths: Iterable[Path | str],
141
  chunk_size: int | None = None,
142
  chunk_overlap: int | None = None,
143
- chunker: RecursiveCharacterTextSplitter | None = None,
 
 
144
  ) -> list[Document]:
145
- if chunker is not None and (
146
- chunk_size is not None
147
- or chunk_overlap is not None
148
- ):
149
- raise ValueError(
150
- "Pass either chunker or chunk_size/chunk_overlap, "
151
- "not both."
152
- )
153
-
154
- page_documents: list[Document] = []
155
-
156
  for path in pdf_paths:
157
- page_documents.extend(
158
- _load_pdf(Path(path))
 
 
 
 
 
159
  )
160
 
161
- if not page_documents:
162
- return []
163
-
164
- splitter = chunker or _splitter(
165
- chunk_size=chunk_size,
166
- chunk_overlap=chunk_overlap,
167
- )
168
-
169
- chunks = splitter.split_documents(page_documents)
170
-
171
- # Mỗi tài liệu và mỗi trang có bộ đếm chunk riêng.
172
- per_page_counter: defaultdict[
173
- tuple[str, int],
174
- int,
175
- ] = defaultdict(int)
176
 
 
177
  for chunk in chunks:
178
- document_id = str(
179
- chunk.metadata["document_id"]
180
- )
181
- page = int(chunk.metadata["page"])
182
- counter_key = (document_id, page)
183
-
184
- index = per_page_counter[counter_key]
185
- per_page_counter[counter_key] += 1
186
-
187
- metadata = ChunkMetadata(
188
- document_id=document_id,
189
- filename=str(chunk.metadata["filename"]),
190
- source=str(chunk.metadata["source"]),
191
- page=page,
192
- chunk_id=_chunk_id(
193
- document_id=document_id,
194
- page=page,
195
- index=index,
196
- ),
197
  section=chunk.metadata.get("section"),
198
  )
199
-
200
- chunk.metadata = metadata.model_dump(
201
- exclude_none=True
202
- )
203
-
204
  return chunks
205
 
206
 
207
- def index_chunks(
208
- chunks: Sequence[Document],
209
- collection_name: str | None = None,
210
- ) -> int:
 
211
  if not chunks:
212
  return 0
 
 
 
213
 
214
- ids = [
215
- str(
216
- uuid.uuid5(
217
- uuid.NAMESPACE_URL,
218
- str(chunk.metadata["chunk_id"]),
219
- )
220
- )
221
- for chunk in chunks
222
- ]
223
-
224
- vector_store = get_vector_store(
225
- collection_name=collection_name
226
- )
227
-
228
- vector_store.add_documents(
229
- documents=list(chunks),
230
- ids=ids,
231
- )
232
 
233
- return len(chunks)
 
 
 
 
 
 
 
 
 
 
 
 
 
234
 
235
 
236
  def ingest(
237
  recreate: bool = False,
238
  collection_name: str | None = None,
239
- chunker: RecursiveCharacterTextSplitter | None = None,
240
  chunk_size: int | None = None,
241
  chunk_overlap: int | None = None,
242
  ) -> int:
243
  pdfs = discover_pdfs()
 
 
 
244
 
245
- ensure_collection(
246
- recreate=recreate,
247
- collection_name=collection_name,
248
- )
249
-
250
  chunks = build_chunks(
251
- pdf_paths=pdfs,
252
  chunker=chunker,
253
  chunk_size=chunk_size,
254
  chunk_overlap=chunk_overlap,
255
  )
256
 
257
- return index_chunks(
258
- chunks=chunks,
259
- collection_name=collection_name,
260
- )
261
 
 
 
 
 
262
 
263
- def save_and_ingest_pdf(
264
- file_bytes: bytes,
265
- filename: str,
266
- collection_name: str | None = None,
267
- ) -> dict[str, str | int]:
 
 
 
 
 
268
  if not file_bytes:
269
  raise ValueError("Uploaded file is empty.")
 
 
 
 
 
 
270
 
271
  safe_name = Path(filename).name
272
-
273
- if not safe_name:
274
- raise ValueError("Filename cannot be empty.")
275
-
276
- if Path(safe_name).suffix.lower() != ".pdf":
277
- raise ValueError("Only PDF files are supported.")
278
-
279
- settings.data_dir.mkdir(
280
- parents=True,
281
- exist_ok=True,
282
- )
283
-
284
- destination = settings.data_dir / safe_name
285
- destination.write_bytes(file_bytes)
286
-
287
- ensure_collection(
288
- recreate=False,
289
- collection_name=collection_name,
290
- )
291
-
292
- chunks = build_chunks([destination])
293
-
294
- chunks_indexed = index_chunks(
295
- chunks=chunks,
296
- collection_name=collection_name,
297
- )
298
-
299
- return {
300
- "filename": safe_name,
301
- "document_id": _document_id(destination),
302
- "chunks_indexed": chunks_indexed,
303
- }
 
 
 
 
 
 
 
1
+ """Load PDFs, split into chunks with metadata, and index into Qdrant."""
2
+
3
+ from __future__ import annotations
4
+
5
  import hashlib
6
+ import os
7
+ import tempfile
8
  import uuid
9
  from collections import defaultdict
 
10
  from pathlib import Path
11
+ from typing import Protocol
12
 
13
  from langchain_community.document_loaders import PyPDFLoader
14
  from langchain_core.documents import Document
15
  from langchain_text_splitters import RecursiveCharacterTextSplitter
16
+ from loguru import logger
17
 
18
+ from src.config import settings
19
+ from src.schemas import ChunkMetadata
20
+ from src.store import delete_old_document_versions, ensure_collection, get_vector_store
 
21
 
22
+ _PDF_SIGNATURE = b"%PDF-"
 
 
 
 
23
 
 
24
 
25
+ class Chunker(Protocol):
26
+ def split_documents(self, documents: list[Document]) -> list[Document]:
27
+ """Split page-level documents into chunk-level documents."""
28
+ ...
29
 
 
 
 
 
 
 
30
 
31
+ def _splitter(
32
+ chunk_size: int | None = None, chunk_overlap: int | None = None
33
+ ) -> RecursiveCharacterTextSplitter:
34
+ size = settings.chunk_size if chunk_size is None else chunk_size
35
+ overlap = settings.chunk_overlap if chunk_overlap is None else chunk_overlap
36
 
37
+ return RecursiveCharacterTextSplitter(
38
+ chunk_size=size,
39
+ chunk_overlap=overlap,
40
+ separators=["\n\n", "\n", ". ", " ", ""],
41
+ keep_separator=False,
 
 
 
 
 
 
 
 
42
  )
43
 
44
 
45
+ def _document_id(path: Path, filename: str | None = None) -> str:
46
+ """Build a stable identity from the logical filename and complete file content."""
47
+ digest = hashlib.sha256()
48
+ digest.update((filename or path.name).encode("utf-8"))
49
+ digest.update(b"\0")
50
+ with path.open("rb") as file_obj:
51
+ for block in iter(lambda: file_obj.read(1024 * 1024), b""):
52
+ digest.update(block)
53
+ return digest.hexdigest()[:24]
54
 
 
 
 
 
55
 
56
+ def _chunk_id(doc_id: str, page: int, index: int) -> str:
57
+ return f"{doc_id}:{page}:{index}"
 
 
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ def _load_pdf(
61
+ path: Path,
62
+ *,
63
+ filename: str | None = None,
64
+ source: str | None = None,
65
+ ) -> list[Document]:
66
+ loader = PyPDFLoader(str(path))
67
+ pages = loader.load()
68
+ logical_filename = filename or path.name
69
+ doc_id = _document_id(path, logical_filename)
70
+ for doc in pages:
71
+ page_number = int(doc.metadata.get("page", 0)) + 1
72
+ doc.metadata = {
73
+ "document_id": doc_id,
74
+ "filename": logical_filename,
75
+ "source": source or logical_filename,
76
+ "page": page_number,
77
+ "section": doc.metadata.get("section"),
78
+ }
79
  return pages
80
 
81
 
82
+ def discover_pdfs(data_dir: Path | None = None) -> list[Path]:
83
+ directory = data_dir or settings.data_dir
84
+ if not directory.exists():
85
+ return []
86
+ return sorted(p for p in directory.iterdir() if p.is_file() and p.suffix.lower() == ".pdf")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
 
89
  def build_chunks(
90
+ pdf_paths: list[Path],
91
  chunk_size: int | None = None,
92
  chunk_overlap: int | None = None,
93
+ chunker: Chunker | None = None,
94
+ filename_override: str | None = None,
95
+ source_override: str | None = None,
96
  ) -> list[Document]:
97
+ page_docs: list[Document] = []
 
 
 
 
 
 
 
 
 
 
98
  for path in pdf_paths:
99
+ logger.info("Loading PDF: {}", path.name)
100
+ page_docs.extend(
101
+ _load_pdf(
102
+ path,
103
+ filename=filename_override,
104
+ source=source_override,
105
+ )
106
  )
107
 
108
+ if chunker is None:
109
+ chunks = _splitter(chunk_size, chunk_overlap).split_documents(page_docs)
110
+ else:
111
+ chunks = chunker.split_documents(page_docs)
 
 
 
 
 
 
 
 
 
 
 
112
 
113
+ per_doc_counter: dict[str, int] = defaultdict(int)
114
  for chunk in chunks:
115
+ doc_id = chunk.metadata["document_id"]
116
+ idx = per_doc_counter[doc_id]
117
+ per_doc_counter[doc_id] += 1
118
+ meta = ChunkMetadata(
119
+ document_id=doc_id,
120
+ filename=chunk.metadata["filename"],
121
+ source=chunk.metadata["source"],
122
+ page=chunk.metadata["page"],
123
+ chunk_id=_chunk_id(doc_id, chunk.metadata["page"], idx),
 
 
 
 
 
 
 
 
 
 
124
  section=chunk.metadata.get("section"),
125
  )
126
+ chunk.metadata = meta.model_dump()
 
 
 
 
127
  return chunks
128
 
129
 
130
+ def index_chunks(chunks: list[Document], collection_name: str | None = None) -> int:
131
+ """Compute deterministic UUIDs and add chunks to the vector store.
132
+
133
+ Re-ingesting the same content upserts instead of creating duplicates.
134
+ """
135
  if not chunks:
136
  return 0
137
+ ids = [str(uuid.uuid5(uuid.NAMESPACE_DNS, c.metadata["chunk_id"])) for c in chunks]
138
+ get_vector_store(collection_name=collection_name).add_documents(chunks, ids=ids)
139
+ return len(chunks)
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
+ def _remove_stale_versions(
143
+ chunks: list[Document],
144
+ collection_name: str | None = None,
145
+ ) -> None:
146
+ """Remove older vector versions after all replacement chunks are available."""
147
+ current_versions = {
148
+ (str(chunk.metadata["filename"]), str(chunk.metadata["document_id"])) for chunk in chunks
149
+ }
150
+ for filename, document_id in current_versions:
151
+ delete_old_document_versions(
152
+ filename,
153
+ document_id,
154
+ collection_name=collection_name,
155
+ )
156
 
157
 
158
  def ingest(
159
  recreate: bool = False,
160
  collection_name: str | None = None,
161
+ chunker: Chunker | None = None,
162
  chunk_size: int | None = None,
163
  chunk_overlap: int | None = None,
164
  ) -> int:
165
  pdfs = discover_pdfs()
166
+ if not pdfs:
167
+ logger.warning("No PDF files found in {}", settings.data_dir)
168
+ return 0
169
 
170
+ ensure_collection(recreate=recreate, collection_name=collection_name)
 
 
 
 
171
  chunks = build_chunks(
172
+ pdfs,
173
  chunker=chunker,
174
  chunk_size=chunk_size,
175
  chunk_overlap=chunk_overlap,
176
  )
177
 
178
+ if not chunks:
179
+ logger.warning("No chunks produced from {} PDF(s)", len(pdfs))
180
+ return 0
 
181
 
182
+ count = index_chunks(chunks, collection_name=collection_name)
183
+ _remove_stale_versions(chunks, collection_name=collection_name)
184
+ logger.info("Ingested {} chunks from {} PDF(s)", count, len(pdfs))
185
+ return count
186
 
187
+
188
+ def save_and_ingest_pdf(file_bytes: bytes, filename: str) -> dict[str, object]:
189
+ """Save an uploaded PDF to `data_dir` and ingest it into Qdrant.
190
+
191
+ Args: file_bytes, filename. Returns: {"filename", "chunks_indexed"}. Raises: ValueError.
192
+ """
193
+ if not filename:
194
+ raise ValueError("Filename is required.")
195
+ if not filename.lower().endswith(".pdf"):
196
+ raise ValueError("Only PDF files are accepted.")
197
  if not file_bytes:
198
  raise ValueError("Uploaded file is empty.")
199
+ if len(file_bytes) > settings.max_upload_bytes:
200
+ raise ValueError(
201
+ f"PDF exceeds the {settings.max_upload_bytes // (1024 * 1024)} MiB upload limit."
202
+ )
203
+ if not file_bytes.startswith(_PDF_SIGNATURE):
204
+ raise ValueError("Uploaded content is not a PDF file.")
205
 
206
  safe_name = Path(filename).name
207
+ if safe_name in {"", ".", ".."}:
208
+ raise ValueError("Filename is invalid.")
209
+ settings.data_dir.mkdir(parents=True, exist_ok=True)
210
+ dest = settings.data_dir / safe_name
211
+ temporary_path: Path | None = None
212
+ try:
213
+ with tempfile.NamedTemporaryFile(
214
+ dir=settings.data_dir,
215
+ prefix=".upload-",
216
+ suffix=".pdf",
217
+ delete=False,
218
+ ) as temporary:
219
+ temporary.write(file_bytes)
220
+ temporary_path = Path(temporary.name)
221
+
222
+ chunks = build_chunks(
223
+ [temporary_path],
224
+ filename_override=safe_name,
225
+ source_override=safe_name,
226
+ )
227
+ if not chunks:
228
+ raise ValueError("Uploaded PDF contains no indexable text.")
229
+
230
+ ensure_collection(recreate=False)
231
+ count = index_chunks(chunks)
232
+ document_id = str(chunks[0].metadata["document_id"])
233
+ os.replace(temporary_path, dest)
234
+ temporary_path = None
235
+ _remove_stale_versions(chunks)
236
+ logger.info("Saved and indexed {} chunks from {}", count, safe_name)
237
+ return {
238
+ "filename": safe_name,
239
+ "document_id": document_id,
240
+ "chunks_indexed": count,
241
+ }
242
+ finally:
243
+ if temporary_path is not None:
244
+ temporary_path.unlink(missing_ok=True)
src/interfaces/README.md CHANGED
@@ -1,8 +1,10 @@
1
- Interfaces
2
 
3
- The src/interfaces/ directory provides the system’s user-facing interfaces:
 
 
 
 
4
 
5
- * api.py — Implements a REST API using FastAPI.
6
- * cli.py — Provides a command-line interface.
7
- * ui.py — Builds the Streamlit web interface.
8
- * styles.py — Contains CSS styles for formatting the web interface.
 
1
+ # Interfaces
2
 
3
+ - `api.py`: FastAPI routes for health, documents, upload, Q&A, summaries, quiz,
4
+ and flashcards.
5
+ - `cli.py`: Typer CLI exposed as the `doculearn-rag` console command
6
+ (`notebooklm` remains as a compatibility alias).
7
+ - `app.py` at the project root: Gradio web interface.
8
 
9
+ All interfaces call the same modules in `src` and share validation, filtering,
10
+ indexing, retrieval, and generation behavior.
 
 
src/interfaces/api.py CHANGED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI entrypoint for the DocuLearn-RAG learning service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ from typing import Annotated
7
+
8
+ from fastapi import FastAPI as _FastAPI
9
+ from fastapi import File, Header, HTTPException, UploadFile, status
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+ from starlette.concurrency import run_in_threadpool
12
+
13
+ from src.config import settings
14
+ from src.filters import MetadataFilter, filters_to_dict
15
+ from src.indexing import save_and_ingest_pdf
16
+ from src.learning import generate_flashcards, generate_quiz
17
+ from src.learning import summarize as summarize_learning
18
+ from src.rag import answer
19
+ from src.schemas import FlashcardSet, QuizSet, RagAnswer, Summary
20
+ from src.store import list_documents
21
+
22
+
23
+ class StrictRequest(BaseModel):
24
+ """Reject misspelled request fields instead of silently ignoring them."""
25
+
26
+ model_config = ConfigDict(extra="forbid")
27
+
28
+
29
+ class AskRequest(StrictRequest):
30
+ question: str = Field(min_length=1)
31
+ k: int | None = Field(default=None, ge=1, le=64)
32
+ filters: MetadataFilter | None = None
33
+
34
+
35
+ class SummarizeRequest(StrictRequest):
36
+ document: str | None = None
37
+ query: str | None = None
38
+ filters: MetadataFilter | None = None
39
+ k: int | None = Field(default=None, ge=1, le=64)
40
+
41
+
42
+ class QuizRequest(SummarizeRequest):
43
+ count: int | None = Field(default=None, ge=1, le=50)
44
+
45
+
46
+ class FlashcardsRequest(SummarizeRequest):
47
+ count: int | None = Field(default=None, ge=1, le=100)
48
+
49
+
50
+ class HealthResponse(BaseModel):
51
+ status: str
52
+
53
+
54
+ class DocumentInfo(BaseModel):
55
+ filename: str
56
+ document_id: str
57
+ pages: list[int]
58
+ page_count: int
59
+ chunk_count: int
60
+
61
+
62
+ class UploadResponse(BaseModel):
63
+ filename: str
64
+ document_id: str
65
+ chunks_indexed: int
66
+
67
+
68
+ app = _FastAPI(
69
+ title="DocuLearn-RAG API",
70
+ description="Grounded Q&A, summaries, quizzes, and flashcards over indexed PDFs.",
71
+ version="0.1.0",
72
+ )
73
+
74
+
75
+ def _require_api_key(x_api_key: Annotated[str | None, Header()] = None) -> None:
76
+ """Protect data and generation routes when RAG_API_KEY is configured."""
77
+ expected = settings.api_key
78
+ if expected is None:
79
+ return
80
+ if x_api_key is None or not secrets.compare_digest(x_api_key, expected):
81
+ raise HTTPException(
82
+ status_code=status.HTTP_401_UNAUTHORIZED,
83
+ detail="Missing or invalid API key.",
84
+ )
85
+
86
+
87
+ @app.get("/health", response_model=HealthResponse)
88
+ def health() -> HealthResponse:
89
+ return HealthResponse(status="ok")
90
+
91
+
92
+ @app.get("/documents", response_model=list[DocumentInfo])
93
+ def documents(
94
+ x_api_key: Annotated[str | None, Header()] = None,
95
+ ) -> list[dict[str, object]]:
96
+ _require_api_key(x_api_key)
97
+ return list_documents()
98
+
99
+
100
+ @app.post("/upload", response_model=UploadResponse)
101
+ async def upload(
102
+ file: Annotated[UploadFile, File()],
103
+ x_api_key: Annotated[str | None, Header()] = None,
104
+ ) -> dict[str, object]:
105
+ _require_api_key(x_api_key)
106
+ content = await file.read(settings.max_upload_bytes + 1)
107
+ if len(content) > settings.max_upload_bytes:
108
+ raise HTTPException(
109
+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
110
+ detail=f"PDF exceeds the {settings.max_upload_bytes}-byte upload limit.",
111
+ )
112
+ try:
113
+ return await run_in_threadpool(save_and_ingest_pdf, content, file.filename or "")
114
+ except ValueError as exc:
115
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
116
+ except (OSError, RuntimeError) as exc:
117
+ raise HTTPException(
118
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
119
+ detail="The document could not be indexed.",
120
+ ) from exc
121
+
122
+
123
+ @app.post("/ask", response_model=RagAnswer)
124
+ def ask(
125
+ request: AskRequest,
126
+ x_api_key: Annotated[str | None, Header()] = None,
127
+ ) -> RagAnswer:
128
+ _require_api_key(x_api_key)
129
+ return answer(
130
+ request.question,
131
+ k=request.k,
132
+ filters=filters_to_dict(request.filters),
133
+ )
134
+
135
+
136
+ @app.post("/summarize", response_model=Summary)
137
+ def summarize(
138
+ request: SummarizeRequest,
139
+ x_api_key: Annotated[str | None, Header()] = None,
140
+ ) -> Summary:
141
+ _require_api_key(x_api_key)
142
+ return summarize_learning(
143
+ document=request.document,
144
+ query=request.query,
145
+ filters=filters_to_dict(request.filters),
146
+ k=request.k,
147
+ )
148
+
149
+
150
+ @app.post("/quiz", response_model=QuizSet)
151
+ def quiz(
152
+ request: QuizRequest,
153
+ x_api_key: Annotated[str | None, Header()] = None,
154
+ ) -> QuizSet:
155
+ _require_api_key(x_api_key)
156
+ return generate_quiz(
157
+ document=request.document,
158
+ query=request.query,
159
+ filters=filters_to_dict(request.filters),
160
+ count=request.count,
161
+ k=request.k,
162
+ )
163
+
164
+
165
+ @app.post("/flashcards", response_model=FlashcardSet)
166
+ def flashcards(
167
+ request: FlashcardsRequest,
168
+ x_api_key: Annotated[str | None, Header()] = None,
169
+ ) -> FlashcardSet:
170
+ _require_api_key(x_api_key)
171
+ return generate_flashcards(
172
+ document=request.document,
173
+ query=request.query,
174
+ filters=filters_to_dict(request.filters),
175
+ count=request.count,
176
+ k=request.k,
177
+ )
src/interfaces/cli.py CHANGED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typer command-line entrypoint for DocuLearn-RAG."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import typer
9
+ from pydantic import BaseModel, ValidationError
10
+
11
+ from src.export import ExportFormat, export
12
+ from src.filters import MetadataFilter, filters_to_dict
13
+ from src.indexing import ingest as ingest_data
14
+ from src.learning import generate_flashcards, generate_quiz
15
+ from src.learning import summarize as summarize_learning
16
+ from src.rag import answer, retrieve
17
+ from src.schemas import RetrievedChunk
18
+
19
+ app = typer.Typer(help="Index PDFs and use grounded DocuLearn-RAG learning features.")
20
+
21
+
22
+ def _parse_filters(value: str | None) -> MetadataFilter | None:
23
+ if value is None or not value.strip():
24
+ return None
25
+
26
+ parsed: dict[str, object] = {}
27
+ allowed = set(MetadataFilter.model_fields)
28
+ for expression in value.split(","):
29
+ key, separator, raw_value = expression.partition("=")
30
+ key = key.strip()
31
+ raw_value = raw_value.strip()
32
+ if not separator or not key or not raw_value:
33
+ raise typer.BadParameter("Filters must use key=value pairs separated by commas.")
34
+ if key not in allowed:
35
+ raise typer.BadParameter(
36
+ f"Unknown filter '{key}'. Expected one of: {', '.join(sorted(allowed))}."
37
+ )
38
+ if key == "page":
39
+ try:
40
+ parsed[key] = int(raw_value)
41
+ except ValueError as error:
42
+ raise typer.BadParameter("The page filter must be an integer.") from error
43
+ elif key == "filenames":
44
+ parsed[key] = [item.strip() for item in raw_value.split("|") if item.strip()]
45
+ else:
46
+ parsed[key] = raw_value
47
+
48
+ try:
49
+ return MetadataFilter.model_validate(parsed)
50
+ except ValidationError as error:
51
+ raise typer.BadParameter(str(error)) from error
52
+
53
+
54
+ def _write_result(
55
+ result: BaseModel,
56
+ output: Path | None,
57
+ fmt: ExportFormat,
58
+ ) -> None:
59
+ rendered = export(result, fmt=fmt, output=output)
60
+ if output is None:
61
+ typer.echo(rendered, nl=False)
62
+ else:
63
+ typer.echo(f"Exported to {rendered}")
64
+
65
+
66
+ def _print_sources(chunks: list[RetrievedChunk]) -> None:
67
+ if not chunks:
68
+ return
69
+ typer.echo("\nSources:")
70
+ for index, chunk in enumerate(chunks, start=1):
71
+ metadata = chunk.metadata
72
+ typer.echo(f"S{index}: {metadata.filename}, page {metadata.page}")
73
+
74
+
75
+ @app.command()
76
+ def ingest(recreate: bool = False) -> None:
77
+ """Index all PDFs in the configured data directory."""
78
+ count = ingest_data(recreate=recreate)
79
+ typer.echo(f"Done. {count} chunks indexed.")
80
+
81
+
82
+ @app.command()
83
+ def ask(
84
+ question: str,
85
+ k: int | None = None,
86
+ filters: str | None = None,
87
+ ) -> None:
88
+ """Ask a grounded question and show its retrieved sources."""
89
+ result = answer(question, k=k, filters=filters_to_dict(_parse_filters(filters)))
90
+ typer.echo(result.answer)
91
+ _print_sources(result.chunks)
92
+
93
+
94
+ @app.command("debug-retrieval")
95
+ def debug_retrieval(
96
+ question: str,
97
+ k: int | None = None,
98
+ filters: str | None = None,
99
+ as_json: bool = False,
100
+ ) -> None:
101
+ """Inspect the chunks retrieved for a question."""
102
+ chunks = retrieve(question, k=k, filters=filters_to_dict(_parse_filters(filters)))
103
+ if as_json:
104
+ typer.echo(
105
+ json.dumps(
106
+ [chunk.model_dump(mode="json") for chunk in chunks],
107
+ ensure_ascii=False,
108
+ indent=2,
109
+ )
110
+ )
111
+ return
112
+ for index, chunk in enumerate(chunks, start=1):
113
+ metadata = chunk.metadata
114
+ typer.echo(
115
+ f"S{index} {metadata.filename} p.{metadata.page} "
116
+ f"score={chunk.score:.4f}\n{chunk.text}\n"
117
+ )
118
+
119
+
120
+ @app.command()
121
+ def summarize(
122
+ document: str | None = None,
123
+ query: str | None = None,
124
+ filters: str | None = None,
125
+ k: int | None = None,
126
+ output: Path | None = None,
127
+ fmt: ExportFormat = "text",
128
+ ) -> None:
129
+ """Create a grounded summary."""
130
+ result = summarize_learning(
131
+ document=document,
132
+ query=query,
133
+ filters=filters_to_dict(_parse_filters(filters)),
134
+ k=k,
135
+ )
136
+ _write_result(result, output, fmt)
137
+
138
+
139
+ @app.command()
140
+ def quiz(
141
+ document: str | None = None,
142
+ query: str | None = None,
143
+ filters: str | None = None,
144
+ count: int | None = None,
145
+ k: int | None = None,
146
+ output: Path | None = None,
147
+ fmt: ExportFormat = "text",
148
+ ) -> None:
149
+ """Generate a grounded multiple-choice quiz."""
150
+ result = generate_quiz(
151
+ document=document,
152
+ query=query,
153
+ filters=filters_to_dict(_parse_filters(filters)),
154
+ count=count,
155
+ k=k,
156
+ )
157
+ _write_result(result, output, fmt)
158
+
159
+
160
+ @app.command()
161
+ def flashcards(
162
+ document: str | None = None,
163
+ query: str | None = None,
164
+ filters: str | None = None,
165
+ count: int | None = None,
166
+ k: int | None = None,
167
+ output: Path | None = None,
168
+ fmt: ExportFormat = "text",
169
+ ) -> None:
170
+ """Generate grounded flashcards."""
171
+ result = generate_flashcards(
172
+ document=document,
173
+ query=query,
174
+ filters=filters_to_dict(_parse_filters(filters)),
175
+ count=count,
176
+ k=k,
177
+ )
178
+ _write_result(result, output, fmt)
179
+
180
+
181
+ if __name__ == "__main__":
182
+ app()
src/interfaces/styles.py DELETED
File without changes
src/interfaces/ui.py DELETED
File without changes
src/learning.py CHANGED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grounded learning features: summarization, quiz, and flashcard generation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Literal
7
+
8
+ from loguru import logger
9
+ from pydantic import ValidationError
10
+
11
+ from src.config import settings
12
+ from src.llm import invoke_llm
13
+ from src.rag import fetch_all_chunks, format_citations, render_prompt, retrieve
14
+ from src.schemas import Flashcard, FlashcardSet, QuizItem, QuizSet, RetrievedChunk, Summary
15
+
16
+ SUMMARY_SINGLE_TEMPLATE = "summary_single.jinja2"
17
+ SUMMARY_MAP_TEMPLATE = "summary_map.jinja2"
18
+ SUMMARY_REDUCE_TEMPLATE = "summary_reduce.jinja2"
19
+ QUIZ_TEMPLATE = "quiz.jinja2"
20
+ FLASHCARDS_TEMPLATE = "flashcards.jinja2"
21
+
22
+
23
+ Scope = Literal["query", "document", "filter", "corpus"]
24
+
25
+
26
+ def _parse_json(text: str) -> dict[str, object] | list[object]:
27
+ """Parse JSON object/array from model output, allowing optional markdown code fences."""
28
+ cleaned = text.strip()
29
+ if cleaned.startswith("```"):
30
+ cleaned = cleaned.split("\n", 1)[-1].removesuffix("```").strip()
31
+
32
+ try:
33
+ obj = json.loads(cleaned)
34
+ except json.JSONDecodeError as e:
35
+ raise RuntimeError(f"Invalid JSON from model output: {cleaned}") from e
36
+
37
+ if not isinstance(obj, (dict, list)):
38
+ raise RuntimeError(f"Expected JSON object or array, got {type(obj).__name__}.")
39
+
40
+ return obj
41
+
42
+
43
+ def _resolve_target(
44
+ document: str | None,
45
+ query: str | None,
46
+ filters: dict[str, object] | None,
47
+ k: int | None,
48
+ retrieval_k: int,
49
+ ) -> tuple[list[RetrievedChunk], Scope, str | None]:
50
+ """Resolve input options into (chunks, scope, target_label)."""
51
+ effective_filters: dict[str, object] = dict(filters or {})
52
+ if document:
53
+ effective_filters["filename"] = document
54
+
55
+ if query:
56
+ chunks = retrieve(query, k=k or retrieval_k, filters=effective_filters)
57
+ target: str | None = query
58
+ scope = "query"
59
+ elif effective_filters:
60
+ chunks = fetch_all_chunks(filters=effective_filters)
61
+ target = ", ".join(f"{fk}={fv}" for fk, fv in effective_filters.items())
62
+ scope = "document" if document else "filter"
63
+ else:
64
+ chunks = fetch_all_chunks(filters=None)
65
+ target = None
66
+ scope = "corpus"
67
+
68
+ return chunks, scope, target
69
+
70
+
71
+ def _validate_items[LearningItem: (QuizItem, Flashcard)](
72
+ payload: object,
73
+ key: str,
74
+ model_class: type[LearningItem],
75
+ dedup_field: str,
76
+ label: str,
77
+ valid_markers: set[str],
78
+ ) -> list[LearningItem]:
79
+ if not isinstance(payload, dict):
80
+ raise RuntimeError(f"Expected JSON object for {label}.")
81
+ raw_items = payload.get(key)
82
+ if not isinstance(raw_items, list):
83
+ raise RuntimeError(f"Expected '{key}' to be a list for {label}.")
84
+
85
+ items: list[LearningItem] = []
86
+ seen: set[str] = set()
87
+ for raw in raw_items:
88
+ if not isinstance(raw, dict):
89
+ continue
90
+ try:
91
+ item = model_class.model_validate(raw)
92
+ except ValidationError as e:
93
+ logger.warning("Dropping invalid {}: {}", label, e)
94
+ continue
95
+ norm = str(getattr(item, dedup_field, "")).strip().lower()
96
+ if not norm or norm in seen:
97
+ continue
98
+ seen.add(norm)
99
+ markers = [m for m in item.source_markers if m in valid_markers]
100
+ if not markers:
101
+ logger.warning("Dropping ungrounded {} without a valid source marker", label)
102
+ continue
103
+ items.append(item.model_copy(update={"source_markers": markers}))
104
+
105
+ if not items:
106
+ raise RuntimeError(f"No valid {label} produced.")
107
+ return items
108
+
109
+
110
+ def _validate_summary_payload(payload: object) -> tuple[str, list[str]]:
111
+ if not isinstance(payload, dict):
112
+ raise RuntimeError("Expected a JSON object for summary.")
113
+ summary = payload.get("summary")
114
+ key_points = payload.get("key_points", [])
115
+ if not isinstance(summary, str):
116
+ raise RuntimeError("Summary payload missing 'summary' string.")
117
+ if not isinstance(key_points, list) or not all(isinstance(x, str) for x in key_points):
118
+ raise RuntimeError("Summary payload 'key_points' must be a list of strings.")
119
+ return summary.strip(), [kp.strip() for kp in key_points if kp.strip()]
120
+
121
+
122
+ def summarize(
123
+ document: str | None = None,
124
+ query: str | None = None,
125
+ filters: dict[str, object] | None = None,
126
+ k: int | None = None,
127
+ ) -> Summary:
128
+ """Grounded summary; uses map-reduce when chunk count exceeds batch size."""
129
+ chunks, scope, target = _resolve_target(
130
+ document=document,
131
+ query=query,
132
+ filters=filters,
133
+ k=k,
134
+ retrieval_k=settings.summarize_retrieval_k,
135
+ )
136
+
137
+ if not chunks:
138
+ raise RuntimeError("No chunks available for summarization.")
139
+
140
+ batch_size = settings.summarize_batch_size
141
+ if len(chunks) <= batch_size:
142
+ prompt = render_prompt(SUMMARY_SINGLE_TEMPLATE, chunks=chunks)
143
+ payload = _parse_json(invoke_llm(prompt))
144
+ summary_text, key_points = _validate_summary_payload(payload)
145
+ else:
146
+ n_batches = (len(chunks) + batch_size - 1) // batch_size
147
+ partials: list[dict[str, object]] = []
148
+
149
+ for batch_index, start in enumerate(range(0, len(chunks), batch_size), start=1):
150
+ logger.info("Summarizing batch {}/{}", batch_index, n_batches)
151
+ batch = chunks[start : start + batch_size]
152
+ prompt = render_prompt(SUMMARY_MAP_TEMPLATE, chunks=batch)
153
+ payload = _parse_json(invoke_llm(prompt))
154
+ summary_text, key_points = _validate_summary_payload(payload)
155
+ partials.append({"summary": summary_text, "key_points": key_points})
156
+
157
+ reduce_prompt = render_prompt(SUMMARY_REDUCE_TEMPLATE, partials=partials)
158
+ payload = _parse_json(invoke_llm(reduce_prompt))
159
+ summary_text, key_points = _validate_summary_payload(payload)
160
+
161
+ return Summary(
162
+ scope=scope,
163
+ target=target,
164
+ summary=summary_text,
165
+ key_points=key_points,
166
+ citations=format_citations(chunks),
167
+ )
168
+
169
+
170
+ def generate_quiz(
171
+ document: str | None = None,
172
+ query: str | None = None,
173
+ filters: dict[str, object] | None = None,
174
+ count: int | None = None,
175
+ k: int | None = None,
176
+ ) -> QuizSet:
177
+ """Grounded multiple-choice quiz; raises RuntimeError if output is unparseable."""
178
+ chunks, scope, target = _resolve_target(
179
+ document=document,
180
+ query=query,
181
+ filters=filters,
182
+ k=k,
183
+ retrieval_k=settings.generation_retrieval_k,
184
+ )
185
+ if not chunks:
186
+ raise RuntimeError("No chunks available for quiz generation.")
187
+
188
+ n = count or settings.quiz_default_count
189
+ valid_markers = {f"S{i}" for i in range(1, len(chunks) + 1)}
190
+
191
+ prompt = render_prompt(QUIZ_TEMPLATE, chunks=chunks, count=n)
192
+ payload = _parse_json(invoke_llm(prompt))
193
+ items = _validate_items(payload, "items", QuizItem, "question", "quiz items", valid_markers)
194
+
195
+ return QuizSet(
196
+ scope=scope,
197
+ target=target,
198
+ items=items,
199
+ citations=format_citations(chunks),
200
+ )
201
+
202
+
203
+ def generate_flashcards(
204
+ document: str | None = None,
205
+ query: str | None = None,
206
+ filters: dict[str, object] | None = None,
207
+ count: int | None = None,
208
+ k: int | None = None,
209
+ ) -> FlashcardSet:
210
+ """Generate grounded flashcards, rejecting unparseable model output."""
211
+ chunks, scope, target = _resolve_target(
212
+ document=document,
213
+ query=query,
214
+ filters=filters,
215
+ k=k,
216
+ retrieval_k=settings.generation_retrieval_k,
217
+ )
218
+ if not chunks:
219
+ raise RuntimeError("No chunks available for flashcard generation.")
220
+
221
+ n = count or settings.flashcards_default_count
222
+ valid_markers = {f"S{i}" for i in range(1, len(chunks) + 1)}
223
+
224
+ prompt = render_prompt(FLASHCARDS_TEMPLATE, chunks=chunks, count=n)
225
+ payload = _parse_json(invoke_llm(prompt))
226
+ cards = _validate_items(payload, "cards", Flashcard, "front", "flashcards", valid_markers)
227
+
228
+ return FlashcardSet(
229
+ scope=scope,
230
+ target=target,
231
+ cards=cards,
232
+ citations=format_citations(chunks),
233
+ )
src/llm.py CHANGED
@@ -1,63 +1,42 @@
1
- from functools import lru_cache
2
- from typing import Any, Literal
3
 
4
- from langchain_core.messages import HumanMessage
5
- from langchain_core.language_models.chat_models import BaseChatModel
6
- from langchain_google_genai import ChatGoogleGenerativeAI
7
- from langchain_openai import ChatOpenAI
8
 
9
- from config import settings
10
 
 
 
11
 
 
12
 
13
- def _build_hf_local():
14
- import torch
15
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
16
- from langchain_huggingface import ChatHuggingFace, HuggingFacePipeline
17
 
18
- tokenizer = AutoTokenizer.from_pretrained(settings.hf_model)
19
- model = AutoModelForCausalLM.from_pretrained(settings.hf_model, dtype=torch.bfloat16)
20
 
21
- text_gen = pipeline(
22
- task="text-generation",
23
- model=model,
24
- tokenizer=tokenizer,
25
- device=settings.hf_device,
26
- return_full_text=False,
27
- )
28
- text_gen.generation_config.max_new_tokens = settings.hf_max_new_tokens
29
- text_gen.generation_config.do_sample = settings.llm_temperature > 0
30
 
31
- return ChatHuggingFace(llm=HuggingFacePipeline(pipeline=text_gen))
32
 
33
- def _build_gemini():
34
- return ChatGoogleGenerativeAI(
35
- model=settings.gemini_model,
36
- temperature=settings.llm_temperature,
37
- google_api_key=settings.google_api_key,
38
- )
 
 
 
 
39
 
40
- def _build_vllm():
41
- return ChatOpenAI(
42
- model=settings.hf_model,
43
- openai_api_key=settings.vllm_api_key,
44
- openai_api_base=settings.vllm_api_base,
45
- temperature=settings.llm_temperature,
 
 
46
  )
47
-
48
- @lru_cache(maxsize=4)
49
- def get_llm(provider=None):
50
- provider = provider or settings.llm_provider
51
-
52
- if provider == "hf_local":
53
- return _build_hf_local()
54
- if provider == "gemini":
55
- return _build_gemini()
56
- if provider == "vllm":
57
- return _build_vllm()
58
-
59
- raise ValueError(f"Unknown llm_provider '{provider}'")
60
-
61
- def invoke_llm(prompt, provider=None):
62
- response = get_llm(provider=provider).invoke([HumanMessage(content=prompt)])
63
- return response.content if isinstance(response.content, str) else str(response.content)
 
1
+ """LLM invocation through Gemini API (google-genai)."""
 
2
 
3
+ from __future__ import annotations
 
 
 
4
 
5
+ from contextvars import ContextVar
6
 
7
+ from google import genai
8
+ from google.genai import types
9
 
10
+ from src.config import settings
11
 
12
+ _runtime_api_key: ContextVar[str | None] = ContextVar("runtime_gemini_api_key", default=None)
 
 
 
13
 
 
 
14
 
15
+ def set_runtime_gemini_api_key(api_key: str | None) -> None:
16
+ _runtime_api_key.set(api_key.strip() if isinstance(api_key, str) else None)
 
 
 
 
 
 
 
17
 
 
18
 
19
+ def invoke_llm(prompt: str) -> str:
20
+ """Invoke the configured chat model and return plain text.
21
+
22
+ Args: prompt.
23
+ Returns: assistant text content.
24
+ Raises: RuntimeError if the API key is missing or response is empty.
25
+ """
26
+ api_key = _runtime_api_key.get() or settings.gemini_api_key
27
+ if not api_key:
28
+ raise RuntimeError("Missing Gemini API key. Provide it in the UI or set GEMINI_API_KEY.")
29
 
30
+ client = genai.Client(api_key=api_key)
31
+ resp = client.models.generate_content(
32
+ model=settings.llm_model,
33
+ contents=prompt,
34
+ config=types.GenerateContentConfig(
35
+ temperature=settings.llm_temperature,
36
+ max_output_tokens=settings.llm_max_new_tokens,
37
+ ),
38
  )
39
+ text = (resp.text or "").strip()
40
+ if not text:
41
+ raise RuntimeError("Empty response from Gemini.")
42
+ return text
 
 
 
 
 
 
 
 
 
 
 
 
 
src/prompts/answer.jinja2 ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a precise assistant. Answer the user's question using ONLY the context below.
2
+
3
+ Rules:
4
+ - Use only facts explicitly supported by the context. Do not invent details.
5
+ - 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."
6
+ - Be concise and direct.
7
+ - Write your answer in Vietnamese.
8
+ - Cite support inline using source markers like [S1], [S2].
9
+ - Use only the source markers provided in the context.
10
+ - Do not write filenames, page numbers, or chunk IDs in the answer body.
11
+
12
+ Context:
13
+ {% for c in chunks %}
14
+ ---
15
+ [source={{ "S" ~ loop.index }}]
16
+ {{ c.text }}
17
+ {% endfor %}
18
+
19
+ Question: {{ question }}
20
+
21
+ Answer:
22
+
src/prompts/flashcards.jinja2 ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are generating study flashcards grounded in the provided context.
2
+
3
+ Rules:
4
+ - Generate exactly {{ count }} flashcards.
5
+ - Fronts should ask for a concept, term, distinction, formula, process, or short explanation.
6
+ - Backs must be concise but complete enough for revision.
7
+ - Ground every card in the context. Do not invent facts.
8
+ - Avoid low-value cards that only restate section headings.
9
+ - Avoid duplicate or overly similar cards.
10
+ - Provide at least one [S#] source marker per card when possible.
11
+ - If the context is insufficient for {{ count }} useful cards, produce fewer rather than pad.
12
+ - Write all fronts, backs, hints, and topic labels in Vietnamese.
13
+
14
+ Output STRICTLY valid JSON and no other text, with this exact shape:
15
+ {
16
+ "cards": [
17
+ {
18
+ "front": "string",
19
+ "back": "string",
20
+ "hint": "optional string or null",
21
+ "topic": "optional short topic label or null",
22
+ "source_markers": ["S1"]
23
+ }
24
+ ]
25
+ }
26
+
27
+ Context:
28
+ {% for c in chunks %}
29
+ ---
30
+ [source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
31
+ {{ c.text }}
32
+ {% endfor %}
33
+
34
+ Respond with ONLY the JSON object.
35
+
src/prompts/quiz.jinja2 ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are generating high-quality multiple-choice quiz items grounded in the provided context.
2
+
3
+ Rules:
4
+ - Generate exactly {{ count }} items.
5
+ - Every question must be answerable from the context alone.
6
+ - Provide exactly 4 options per question with exactly one correct answer.
7
+ - Test understanding: concepts, distinctions, reasoning, and factual recall.
8
+ - Avoid duplicates or near-duplicates.
9
+ - Avoid trick questions or ambiguous wording.
10
+ - Explanations must be concise and cite at least one [S#] marker from the context.
11
+ - If the context is insufficient to create {{ count }} high-quality items, generate fewer. Never fabricate facts.
12
+ - Write all questions, options, explanations, and topic labels in Vietnamese.
13
+
14
+ Output STRICTLY valid JSON and no other text, with this exact shape:
15
+ {
16
+ "items": [
17
+ {
18
+ "question": "string",
19
+ "options": ["string", "string", "string", "string"],
20
+ "correct_index": 0,
21
+ "explanation": "grounded explanation with [S1] style citations",
22
+ "source_markers": ["S1"],
23
+ "difficulty": "easy|medium|hard",
24
+ "topic": "short topic label"
25
+ }
26
+ ]
27
+ }
28
+
29
+ Context:
30
+ {% for c in chunks %}
31
+ ---
32
+ [source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
33
+ {{ c.text }}
34
+ {% endfor %}
35
+
36
+ Respond with ONLY the JSON object.
37
+
src/prompts/summary_map.jinja2 ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are summarizing a portion of a learning document for later synthesis.
2
+
3
+ Rules:
4
+ - Summarize only what the passages actually say.
5
+ - Preserve concepts, definitions, processes, and reasoning.
6
+ - Do not add outside knowledge. Do not speculate.
7
+ - Keep it dense but readable; aim for 4-8 sentences.
8
+ - Write the summary and key points in Vietnamese.
9
+
10
+ Output STRICTLY valid JSON with this shape and no extra text:
11
+ {
12
+ "summary": "dense paragraph summary",
13
+ "key_points": ["fact", "fact"]
14
+ }
15
+
16
+ Passages:
17
+ {% for c in chunks %}
18
+ ---
19
+ [source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
20
+ {{ c.text }}
21
+ {% endfor %}
22
+
23
+ Respond with ONLY the JSON object.
24
+
src/prompts/summary_reduce.jinja2 ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are synthesizing partial summaries of a learning document into one coherent study summary.
2
+
3
+ Rules:
4
+ - Use only information present in the partial summaries.
5
+ - Do not add outside knowledge. Do not invent details.
6
+ - Merge duplicated points; preserve distinctions between related concepts.
7
+ - Write for a learner who wants to understand and remember the material.
8
+ - Write the summary and key points in Vietnamese.
9
+
10
+ Output STRICTLY valid JSON with this shape and no extra text:
11
+ {
12
+ "summary": "A coherent multi-paragraph study summary.",
13
+ "key_points": ["concise learnable fact", "concise learnable fact"]
14
+ }
15
+
16
+ Partial summaries:
17
+ {% for p in partials %}
18
+ ---
19
+ Summary: {{ p.summary }}
20
+ {% if p.key_points %}
21
+ Key points:
22
+ {% for kp in p.key_points %}
23
+ - {{ kp }}
24
+ {% endfor %}
25
+ {% endif %}
26
+ {% endfor %}
27
+
28
+ Respond with ONLY the JSON object.
29
+
src/prompts/summary_single.jinja2 ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are writing a study-oriented summary grounded strictly in the provided context.
2
+
3
+ Rules:
4
+ - Use only facts explicitly supported by the context. Do not invent details.
5
+ - Do not add outside knowledge.
6
+ - Focus on concepts, definitions, relationships, and reasoning a learner should retain.
7
+ - Keep the tone clear, neutral, and practical for study.
8
+ - Write the summary and key points in Vietnamese.
9
+ - If the context is empty or unrelated, return an empty summary and an empty list of key points.
10
+
11
+ Output STRICTLY valid JSON with this shape and no extra text:
12
+ {
13
+ "summary": "A coherent multi-paragraph study summary.",
14
+ "key_points": ["concise learnable fact", "concise learnable fact"]
15
+ }
16
+
17
+ Context:
18
+ {% for c in chunks %}
19
+ ---
20
+ [source=S{{ loop.index }}] ({{ c.metadata.filename }} p.{{ c.metadata.page }})
21
+ {{ c.text }}
22
+ {% endfor %}
23
+
24
+ Respond with ONLY the JSON object.
25
+
src/rag.py CHANGED
@@ -1,122 +1,67 @@
 
 
 
 
1
  from functools import lru_cache
2
- from typing import Any
3
 
4
  from jinja2 import Environment, FileSystemLoader, StrictUndefined
5
- from pydantic import ValidationError
6
 
7
- from config import settings
8
- from schemas import (
9
- ChunkMetadata,
10
- Citation,
11
- RagAnswer,
12
- RetrievedChunk,
13
- )
 
14
 
15
 
16
  def retrieve(
17
  query: str,
18
  k: int | None = None,
19
- filters: Any = None,
20
  collection_name: str | None = None,
21
  ) -> list[RetrievedChunk]:
22
- query = query.strip()
23
-
24
- if not query:
25
- raise ValueError("query cannot be empty.")
26
-
27
- resolved_k = settings.top_k if k is None else k
28
-
29
- if resolved_k <= 0:
30
- raise ValueError("k must be greater than 0.")
31
-
32
- hits = get_vector_store(
33
- collection_name=collection_name
34
- ).similarity_search_with_score(
35
  query=query,
36
- k=resolved_k,
37
  filter=filters_to_qdrant(filters),
38
  )
39
-
40
- results: list[RetrievedChunk] = []
41
-
42
- for document, score in hits:
43
- metadata = ChunkMetadata.model_validate(
44
- document.metadata
45
- )
46
-
47
- results.append(
48
- RetrievedChunk(
49
- text=document.page_content,
50
- score=float(score),
51
- metadata=metadata,
52
- )
53
  )
54
-
55
- return results
56
-
57
-
58
- def _chunk_index(chunk_id: str) -> int:
59
- try:
60
- return int(chunk_id.rsplit(":", 1)[-1])
61
- except (TypeError, ValueError):
62
- # Đẩy chunk có ID không hợp lệ xuống cuối.
63
- return 2**31 - 1
64
 
65
 
66
  def fetch_all_chunks(
67
- filters: Any = None,
68
  collection_name: str | None = None,
69
  ) -> list[RetrievedChunk]:
 
70
  name = collection_name or settings.qdrant_collection
71
- qdrant_filter = filters_to_qdrant(filters)
72
-
73
  results: list[RetrievedChunk] = []
74
-
75
- for points in scroll_all(
76
- name,
77
- scroll_filter=qdrant_filter,
78
- ):
79
- for point in points:
80
  payload = point.payload or {}
81
-
82
- metadata_payload = payload.get("metadata")
83
- text_payload = payload.get("page_content")
84
-
85
- if not isinstance(metadata_payload, dict):
86
- continue
87
-
88
- if not isinstance(text_payload, str):
89
  continue
90
-
91
- text = text_payload.strip()
92
-
93
- if not text:
94
- continue
95
-
96
- try:
97
- metadata = ChunkMetadata.model_validate(
98
- metadata_payload
99
- )
100
- except ValidationError:
101
- # Nên log dữ liệu lỗi trong ứng dụng thực tế.
102
- continue
103
-
104
- results.append(
105
- RetrievedChunk(
106
- text=text,
107
- score=0.0,
108
- metadata=metadata,
109
- )
110
- )
111
-
112
- return sorted(
113
- results,
114
- key=lambda result: (
115
- result.metadata.filename.casefold(),
116
- result.metadata.page,
117
- _chunk_index(result.metadata.chunk_id),
118
- ),
119
  )
 
120
 
121
 
122
  @lru_cache(maxsize=1)
@@ -130,89 +75,45 @@ def _jinja_env() -> Environment:
130
  )
131
 
132
 
133
- def render_prompt(
134
- template_name: str,
135
- **context: Any,
136
- ) -> str:
137
- return (
138
- _jinja_env()
139
- .get_template(template_name)
140
- .render(**context)
141
- )
142
 
143
 
144
- def format_citations(
145
- chunks: list[RetrievedChunk],
146
- ) -> list[Citation]:
147
  return [
148
  Citation(
149
- source_index=index,
150
- source_marker=f"S{index}",
151
- filename=chunk.metadata.filename,
152
- page=chunk.metadata.page,
153
- section=chunk.metadata.section,
154
- chunk_id=chunk.metadata.chunk_id,
155
- )
156
- for index, chunk in enumerate(
157
- chunks,
158
- start=1,
159
  )
 
160
  ]
161
 
162
 
163
  def answer(
164
  question: str,
165
  k: int | None = None,
166
- filters: Any = None,
167
  collection_name: str | None = None,
168
  ) -> RagAnswer:
169
- question = question.strip()
170
-
171
- if not question:
172
- raise ValueError("question cannot be empty.")
173
-
174
- chunks = retrieve(
175
- query=question,
176
- k=k,
177
- filters=filters,
178
- collection_name=collection_name,
179
- )
180
-
181
  if not chunks:
182
  return RagAnswer(
183
  question=question,
184
- answer=(
185
- "Tôi không có đủ thông tin trong ngữ cảnh "
186
- "được cung cấp để trả lời."
187
- ),
188
- citations=[],
189
- chunks=[],
190
- )
191
-
192
- prompt = render_prompt(
193
- ANSWER_TEMPLATE,
194
- question=question,
195
- chunks=chunks,
196
- )
197
-
198
- response = invoke_llm(prompt)
199
-
200
- if not isinstance(response, str):
201
- raise TypeError(
202
- "invoke_llm() must return a string."
203
  )
204
 
205
- answer_text = response.strip()
206
-
207
- if not answer_text:
208
- answer_text = (
209
- "Tôi không có đủ thông tin trong ngữ cảnh "
210
- "được cung cấp để trả lời."
211
- )
212
 
213
  return RagAnswer(
214
  question=question,
215
- answer=answer_text,
216
  citations=format_citations(chunks),
217
  chunks=chunks,
218
- )
 
1
+ """Retrieval, prompts, citations, and grounded answers."""
2
+
3
+ from __future__ import annotations
4
+
5
  from functools import lru_cache
6
+ from pathlib import Path
7
 
8
  from jinja2 import Environment, FileSystemLoader, StrictUndefined
 
9
 
10
+ from src.config import settings
11
+ from src.filters import filters_to_qdrant
12
+ from src.llm import invoke_llm
13
+ from src.schemas import ChunkMetadata, Citation, RagAnswer, RetrievedChunk
14
+ from src.store import get_vector_store, scroll_all
15
+
16
+ PROMPTS_DIR = Path(__file__).parent / "prompts"
17
+ ANSWER_TEMPLATE = "answer.jinja2"
18
 
19
 
20
  def retrieve(
21
  query: str,
22
  k: int | None = None,
23
+ filters: dict[str, object] | None = None,
24
  collection_name: str | None = None,
25
  ) -> list[RetrievedChunk]:
26
+ store = get_vector_store(collection_name=collection_name)
27
+ hits = store.similarity_search_with_score(
 
 
 
 
 
 
 
 
 
 
 
28
  query=query,
29
+ k=k or settings.top_k,
30
  filter=filters_to_qdrant(filters),
31
  )
32
+ return [
33
+ RetrievedChunk(
34
+ text=doc.page_content,
35
+ score=float(score),
36
+ metadata=ChunkMetadata(**doc.metadata),
 
 
 
 
 
 
 
 
 
37
  )
38
+ for doc, score in hits
39
+ ]
 
 
 
 
 
 
 
 
40
 
41
 
42
  def fetch_all_chunks(
43
+ filters: dict[str, object] | None = None,
44
  collection_name: str | None = None,
45
  ) -> list[RetrievedChunk]:
46
+ """Scroll every chunk matching the filter, ordered by filename → page → index."""
47
  name = collection_name or settings.qdrant_collection
 
 
48
  results: list[RetrievedChunk] = []
49
+ for page in scroll_all(name, scroll_filter=filters_to_qdrant(filters)):
50
+ for point in page:
 
 
 
 
51
  payload = point.payload or {}
52
+ meta = payload.get("metadata") or {}
53
+ text = payload.get("page_content") or ""
54
+ if not meta or not text:
 
 
 
 
 
55
  continue
56
+ results.append(RetrievedChunk(text=text, score=0.0, metadata=ChunkMetadata(**meta)))
57
+ results.sort(
58
+ key=lambda r: (
59
+ r.metadata.filename,
60
+ r.metadata.page,
61
+ int(r.metadata.chunk_id.rsplit(":", 1)[-1]),
62
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  )
64
+ return results
65
 
66
 
67
  @lru_cache(maxsize=1)
 
75
  )
76
 
77
 
78
+ def render_prompt(template_name: str, **context: object) -> str:
79
+ """Render an arbitrary Jinja template from the prompts directory."""
80
+ return _jinja_env().get_template(template_name).render(**context)
 
 
 
 
 
 
81
 
82
 
83
+ def format_citations(chunks: list[RetrievedChunk]) -> list[Citation]:
 
 
84
  return [
85
  Citation(
86
+ source_index=i,
87
+ source_marker=f"S{i}",
88
+ filename=c.metadata.filename,
89
+ page=c.metadata.page,
90
+ source_text=c.text.strip(),
91
+ section=c.metadata.section,
92
+ chunk_id=c.metadata.chunk_id,
 
 
 
93
  )
94
+ for i, c in enumerate(chunks, start=1)
95
  ]
96
 
97
 
98
  def answer(
99
  question: str,
100
  k: int | None = None,
101
+ filters: dict[str, object] | None = None,
102
  collection_name: str | None = None,
103
  ) -> RagAnswer:
104
+ chunks = retrieve(question, k=k, filters=filters, collection_name=collection_name)
 
 
 
 
 
 
 
 
 
 
 
105
  if not chunks:
106
  return RagAnswer(
107
  question=question,
108
+ answer="Tôi không có đủ thông tin trong ngữ cảnh được cung cấp để trả lời.",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  )
110
 
111
+ prompt = render_prompt(ANSWER_TEMPLATE, question=question, chunks=chunks)
112
+ text = invoke_llm(prompt)
 
 
 
 
 
113
 
114
  return RagAnswer(
115
  question=question,
116
+ answer=text.strip(),
117
  citations=format_citations(chunks),
118
  chunks=chunks,
119
+ )
src/schemas.py CHANGED
@@ -1,77 +1,94 @@
 
 
 
 
1
  from typing import Literal
2
 
3
  from pydantic import BaseModel, Field, model_validator
4
 
 
5
  class ChunkMetadata(BaseModel):
 
 
6
  document_id: str
7
  filename: str
8
  source: str
9
- page: int = Field(ge=0)
10
  chunk_id: str
11
  section: str | None = None
12
 
 
13
  class RetrievedChunk(BaseModel):
 
 
14
  text: str
15
  score: float
16
  metadata: ChunkMetadata
17
 
 
18
  class Citation(BaseModel):
19
- source_index: int = Field(ge=0)
 
 
20
  source_marker: str
21
  filename: str
22
- page: int | None = Field(default=None, ge=0)
 
23
  section: str | None = None
24
  chunk_id: str | None = None
25
 
 
26
  class RagAnswer(BaseModel):
 
 
27
  question: str
28
  answer: str
29
  citations: list[Citation] = Field(default_factory=list)
30
  chunks: list[RetrievedChunk] = Field(default_factory=list)
31
 
 
32
  class Summary(BaseModel):
 
 
33
  scope: Literal["query", "document", "filter", "corpus"]
34
  target: str | None = None
35
  summary: str
36
  key_points: list[str] = Field(default_factory=list)
37
  citations: list[Citation] = Field(default_factory=list)
38
- chunks: list[RetrievedChunk] = Field(default_factory=list)
39
 
40
 
41
  class QuizItem(BaseModel):
42
- question: str
43
-
44
- options: list[str] = Field(
45
- min_length=4,
46
- max_length=4,
47
- )
48
 
 
 
49
  correct_index: int
50
  explanation: str
51
  source_markers: list[str] = Field(default_factory=list)
52
-
53
- difficulty: Literal["easy", "medium", "hard"] | None = None
54
  topic: str | None = None
55
 
56
  @model_validator(mode="after")
57
- def validate_correct_index(self) -> "QuizItem":
58
  if not 0 <= self.correct_index < len(self.options):
59
  raise ValueError(
60
- "correct_index must refer to an existing option."
61
  )
62
-
63
  return self
64
 
65
 
66
  class QuizSet(BaseModel):
 
 
67
  scope: Literal["query", "document", "filter", "corpus"]
68
  target: str | None = None
69
  items: list[QuizItem] = Field(default_factory=list)
70
  citations: list[Citation] = Field(default_factory=list)
71
- chunks: list[RetrievedChunk] = Field(default_factory=list)
72
 
73
 
74
  class Flashcard(BaseModel):
 
 
75
  front: str
76
  back: str
77
  hint: str | None = None
@@ -80,8 +97,9 @@ class Flashcard(BaseModel):
80
 
81
 
82
  class FlashcardSet(BaseModel):
 
 
83
  scope: Literal["query", "document", "filter", "corpus"]
84
  target: str | None = None
85
  cards: list[Flashcard] = Field(default_factory=list)
86
  citations: list[Citation] = Field(default_factory=list)
87
- chunks: list[RetrievedChunk] = Field(default_factory=list)
 
1
+ """Pydantic schemas for chunks, answers, and learning outputs."""
2
+
3
+ from __future__ import annotations
4
+
5
  from typing import Literal
6
 
7
  from pydantic import BaseModel, Field, model_validator
8
 
9
+
10
  class ChunkMetadata(BaseModel):
11
+ """Stable metadata attached to every chunk stored in Qdrant."""
12
+
13
  document_id: str
14
  filename: str
15
  source: str
16
+ page: int
17
  chunk_id: str
18
  section: str | None = None
19
 
20
+
21
  class RetrievedChunk(BaseModel):
22
+ """A retrieved chunk with its score and metadata."""
23
+
24
  text: str
25
  score: float
26
  metadata: ChunkMetadata
27
 
28
+
29
  class Citation(BaseModel):
30
+ """Citation extracted from a retrieved chunk's metadata."""
31
+
32
+ source_index: int
33
  source_marker: str
34
  filename: str
35
+ page: int
36
+ source_text: str | None = None
37
  section: str | None = None
38
  chunk_id: str | None = None
39
 
40
+
41
  class RagAnswer(BaseModel):
42
+ """Final grounded answer returned to the caller."""
43
+
44
  question: str
45
  answer: str
46
  citations: list[Citation] = Field(default_factory=list)
47
  chunks: list[RetrievedChunk] = Field(default_factory=list)
48
 
49
+
50
  class Summary(BaseModel):
51
+ """Grounded study-oriented summary of a document or subset."""
52
+
53
  scope: Literal["query", "document", "filter", "corpus"]
54
  target: str | None = None
55
  summary: str
56
  key_points: list[str] = Field(default_factory=list)
57
  citations: list[Citation] = Field(default_factory=list)
 
58
 
59
 
60
  class QuizItem(BaseModel):
61
+ """A single multiple-choice quiz item grounded in the source material."""
 
 
 
 
 
62
 
63
+ question: str
64
+ options: list[str] = Field(min_length=4, max_length=4)
65
  correct_index: int
66
  explanation: str
67
  source_markers: list[str] = Field(default_factory=list)
68
+ difficulty: str | None = None
 
69
  topic: str | None = None
70
 
71
  @model_validator(mode="after")
72
+ def _validate_correct_index(self) -> QuizItem:
73
  if not 0 <= self.correct_index < len(self.options):
74
  raise ValueError(
75
+ f"correct_index {self.correct_index} out of range for {len(self.options)} options"
76
  )
 
77
  return self
78
 
79
 
80
  class QuizSet(BaseModel):
81
+ """A reusable set of grounded quiz items with resolved citations."""
82
+
83
  scope: Literal["query", "document", "filter", "corpus"]
84
  target: str | None = None
85
  items: list[QuizItem] = Field(default_factory=list)
86
  citations: list[Citation] = Field(default_factory=list)
 
87
 
88
 
89
  class Flashcard(BaseModel):
90
+ """A single study flashcard grounded in the source material."""
91
+
92
  front: str
93
  back: str
94
  hint: str | None = None
 
97
 
98
 
99
  class FlashcardSet(BaseModel):
100
+ """A reusable set of grounded flashcards with resolved citations."""
101
+
102
  scope: Literal["query", "document", "filter", "corpus"]
103
  target: str | None = None
104
  cards: list[Flashcard] = Field(default_factory=list)
105
  citations: list[Citation] = Field(default_factory=list)
 
src/store.py CHANGED
@@ -1,94 +1,188 @@
 
 
 
 
 
1
  from functools import lru_cache
2
 
3
- from langchain_huggingface import HuggingFaceEmbeddings
4
  from langchain_qdrant import QdrantVectorStore
5
  from qdrant_client import QdrantClient
6
- from qdrant_client import models as qmodels
7
-
8
- from config import settings
9
 
 
 
10
 
11
- @lru_cache(maxsize=1)
12
- def get_embeddings() -> HuggingFaceEmbeddings:
13
- return HuggingFaceEmbeddings(
14
- model_name=settings.embedding_model,
15
- model_kwargs={
16
- "device": settings.hf_device,
17
- },
18
- encode_kwargs={
19
- "normalize_embeddings": True,
20
- },
21
- )
22
 
 
 
 
 
 
23
 
24
- @lru_cache(maxsize=1)
25
- def get_client() -> QdrantClient:
26
- settings.storage_dir.mkdir(
27
- parents=True,
28
- exist_ok=True,
29
- )
30
 
31
- return QdrantClient(
32
- path=str(settings.storage_dir),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  )
34
 
35
 
36
- def get_vector_store(
 
 
37
  collection_name: str | None = None,
38
- ) -> QdrantVectorStore:
 
39
  name = collection_name or settings.qdrant_collection
40
-
41
- return QdrantVectorStore(
42
- client=get_client(),
43
  collection_name=name,
44
- embedding=get_embeddings(),
 
 
 
45
  )
46
 
47
 
48
- INDEXED_PAYLOAD_FIELDS: dict[str, qmodels.PayloadSchemaType] = {
49
- "metadata.document_id": qmodels.PayloadSchemaType.KEYWORD,
50
- "metadata.filename": qmodels.PayloadSchemaType.KEYWORD,
51
- "metadata.chunk_id": qmodels.PayloadSchemaType.KEYWORD,
52
- "metadata.page": qmodels.PayloadSchemaType.INTEGER,
53
- }
54
 
55
 
56
- def ensure_collection(
57
- recreate: bool = False,
58
- collection_name: str | None = None,
59
- ) -> None:
 
 
 
 
 
60
  client = get_client()
61
  name = collection_name or settings.qdrant_collection
62
 
63
- exists = client.collection_exists(
64
- collection_name=name,
65
- )
66
-
67
  if exists and recreate:
68
- client.delete_collection(
69
- collection_name=name,
70
- )
71
  exists = False
72
 
73
  if not exists:
74
- embedding_dimension = len(get_embeddings().embed_query("dimension probe"))
75
-
76
  client.create_collection(
77
  collection_name=name,
78
  vectors_config=qmodels.VectorParams(
79
- size=embedding_dimension,
80
  distance=qmodels.Distance.COSINE,
81
  ),
82
  )
83
 
84
- collection_info = client.get_collection(collection_name=name)
85
-
86
- payload_schema = collection_info.payload_schema or {}
87
 
88
  for field_name, field_schema in INDEXED_PAYLOAD_FIELDS.items():
89
- if field_name not in payload_schema:
 
90
  client.create_payload_index(
91
  collection_name=name,
92
  field_name=field_name,
93
  field_schema=field_schema,
94
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Embeddings, Qdrant client, collection setup, and vector store."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
  from functools import lru_cache
7
 
 
8
  from langchain_qdrant import QdrantVectorStore
9
  from qdrant_client import QdrantClient
10
+ from qdrant_client.http import models as qmodels
 
 
11
 
12
+ from src.config import settings
13
+ from src.embeddings import get_embeddings
14
 
15
+ _SCROLL_PAGE_SIZE = 256
 
 
 
 
 
 
 
 
 
 
16
 
17
+ INDEXED_PAYLOAD_FIELDS = {
18
+ "metadata.document_id": qmodels.PayloadSchemaType.KEYWORD,
19
+ "metadata.filename": qmodels.PayloadSchemaType.KEYWORD,
20
+ "metadata.page": qmodels.PayloadSchemaType.INTEGER,
21
+ }
22
 
 
 
 
 
 
 
23
 
24
+ def _old_document_versions_filter(
25
+ filename: str,
26
+ keep_document_id: str,
27
+ ) -> qmodels.Filter:
28
+ """Select older vector versions for one uploaded filename."""
29
+ return qmodels.Filter(
30
+ must=[
31
+ qmodels.FieldCondition(
32
+ key="metadata.filename",
33
+ match=qmodels.MatchValue(value=filename),
34
+ )
35
+ ],
36
+ must_not=[
37
+ qmodels.FieldCondition(
38
+ key="metadata.document_id",
39
+ match=qmodels.MatchValue(value=keep_document_id),
40
+ )
41
+ ],
42
  )
43
 
44
 
45
+ def delete_old_document_versions(
46
+ filename: str,
47
+ keep_document_id: str,
48
  collection_name: str | None = None,
49
+ ) -> None:
50
+ """Delete stale vectors for a filename after its new version is indexed."""
51
  name = collection_name or settings.qdrant_collection
52
+ get_client().delete(
 
 
53
  collection_name=name,
54
+ points_selector=qmodels.FilterSelector(
55
+ filter=_old_document_versions_filter(filename, keep_document_id)
56
+ ),
57
+ wait=True,
58
  )
59
 
60
 
61
+ def close_client() -> None:
62
+ if get_client.cache_info().currsize == 0:
63
+ return
64
+ client = get_client()
65
+ client.close()
66
+ get_client.cache_clear()
67
 
68
 
69
+ @lru_cache(maxsize=1)
70
+ def get_client() -> QdrantClient:
71
+ """Return a cached local Qdrant client backed by on-disk storage."""
72
+ settings.storage_dir.mkdir(parents=True, exist_ok=True)
73
+ return QdrantClient(path=str(settings.storage_dir))
74
+
75
+
76
+ def ensure_collection(recreate: bool = False, collection_name: str | None = None) -> None:
77
+ """Create the collection and payload indexes if they do not exist."""
78
  client = get_client()
79
  name = collection_name or settings.qdrant_collection
80
 
81
+ exists = client.collection_exists(name)
 
 
 
82
  if exists and recreate:
83
+ client.delete_collection(name)
 
 
84
  exists = False
85
 
86
  if not exists:
87
+ dim = len(get_embeddings().embed_query("dimension probe"))
 
88
  client.create_collection(
89
  collection_name=name,
90
  vectors_config=qmodels.VectorParams(
91
+ size=dim,
92
  distance=qmodels.Distance.COSINE,
93
  ),
94
  )
95
 
96
+ payload_schema = client.get_collection(name).payload_schema or {}
 
 
97
 
98
  for field_name, field_schema in INDEXED_PAYLOAD_FIELDS.items():
99
+ existing = payload_schema.get(field_name)
100
+ if existing is None:
101
  client.create_payload_index(
102
  collection_name=name,
103
  field_name=field_name,
104
  field_schema=field_schema,
105
+ )
106
+ continue
107
+
108
+ existing_schema = getattr(existing, "data_type", None)
109
+ if existing_schema != field_schema:
110
+ raise ValueError(
111
+ f"Payload index for '{field_name}' has schema "
112
+ f"{existing_schema!r}, expected {field_schema!r}."
113
+ )
114
+
115
+
116
+ def scroll_all(
117
+ collection_name: str,
118
+ scroll_filter: qmodels.Filter | None = None,
119
+ with_payload: bool | list[str] = True,
120
+ limit: int = _SCROLL_PAGE_SIZE,
121
+ ) -> Iterator[list[qmodels.Record]]:
122
+ """Yield pages of Qdrant points (no vectors) until the collection is exhausted."""
123
+ client = get_client()
124
+ offset = None
125
+ while True:
126
+ try:
127
+ points, next_offset = client.scroll(
128
+ collection_name=collection_name,
129
+ scroll_filter=scroll_filter,
130
+ limit=limit,
131
+ offset=offset,
132
+ with_payload=with_payload,
133
+ with_vectors=False,
134
+ )
135
+ except ValueError as exc:
136
+ # Local Qdrant raises ValueError when collection doesn't exist yet.
137
+ if "not found" in str(exc).lower():
138
+ return
139
+ raise
140
+ yield points
141
+ if next_offset is None:
142
+ break
143
+ offset = next_offset
144
+
145
+
146
+ def get_vector_store(collection_name: str | None = None) -> QdrantVectorStore:
147
+ return QdrantVectorStore(
148
+ client=get_client(),
149
+ collection_name=collection_name or settings.qdrant_collection,
150
+ embedding=get_embeddings(),
151
+ )
152
+
153
+
154
+ def list_documents() -> list[dict[str, object]]:
155
+ """List indexed documents with filename, document_id, pages, and chunk counts.
156
+
157
+ Returns one entry per filename matching the API `DocumentInfo` shape.
158
+ """
159
+ pages_map: dict[str, set[int]] = {}
160
+ doc_id_map: dict[str, str] = {}
161
+ count_map: dict[str, int] = {}
162
+
163
+ for batch in scroll_all(settings.qdrant_collection, with_payload=["metadata"]):
164
+ for point in batch:
165
+ meta = (point.payload or {}).get("metadata") or {}
166
+ filename = meta.get("filename")
167
+ document_id = meta.get("document_id")
168
+ pg = meta.get("page")
169
+ if not filename or not document_id or not isinstance(pg, int):
170
+ continue
171
+ fn = str(filename)
172
+ doc_id_map.setdefault(fn, str(document_id))
173
+ pages_map.setdefault(fn, set()).add(pg)
174
+ count_map[fn] = count_map.get(fn, 0) + 1
175
+
176
+ return sorted(
177
+ [
178
+ {
179
+ "filename": fn,
180
+ "document_id": doc_id_map[fn],
181
+ "pages": sorted(pages_map[fn]),
182
+ "page_count": len(pages_map[fn]),
183
+ "chunk_count": count_map[fn],
184
+ }
185
+ for fn in doc_id_map
186
+ ],
187
+ key=lambda d: str(d["filename"]),
188
+ )
src/ui/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from src.ui.layout import build_demo
2
+ from src.ui.runtime import launch_demo
3
+
4
+ __all__ = ["build_demo", "launch_demo"]
src/ui/callbacks.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ import gradio as gr
6
+
7
+ from src.export import export
8
+ from src.learning import generate_flashcards, generate_quiz, summarize
9
+ from src.llm import set_runtime_gemini_api_key
10
+ from src.rag import answer
11
+ from src.ui.helpers import PROGRESS
12
+ from src.ui.uploads import build_filters
13
+
14
+
15
+ def ask_question(
16
+ question: str,
17
+ k: int,
18
+ selected_docs: list[str],
19
+ page: str,
20
+ gemini_key: str,
21
+ ) -> tuple[str, str]:
22
+ if not question or not question.strip():
23
+ return "Vui lòng nhập câu hỏi.", ""
24
+ page_num = None if page == "(Tất cả trang)" else int(page)
25
+ set_runtime_gemini_api_key(gemini_key)
26
+ result = answer(
27
+ question.strip(),
28
+ k=int(k),
29
+ filters=build_filters(selected_docs, page_num),
30
+ )
31
+ return (
32
+ str(export(result, fmt="md")),
33
+ json.dumps(result.model_dump(), ensure_ascii=False, indent=2),
34
+ )
35
+
36
+
37
+ def ask_chat(
38
+ message: str,
39
+ history: list[dict[str, str]] | None,
40
+ k: int,
41
+ selected_docs: list[str],
42
+ page: str,
43
+ gemini_key: str,
44
+ ) -> tuple[list[dict[str, str]], str, str]:
45
+ user_text = (message or "").strip()
46
+ turns = list(history or [])
47
+ if not user_text:
48
+ return turns, "", ""
49
+ answer_md, raw = ask_question(user_text, k, selected_docs, page, gemini_key)
50
+ turns.append({"role": "user", "content": user_text})
51
+ turns.append({"role": "assistant", "content": answer_md})
52
+ return turns, raw, ""
53
+
54
+
55
+ def summarize_documents(
56
+ query: str,
57
+ k: int,
58
+ selected_docs: list[str],
59
+ page: str,
60
+ gemini_key: str,
61
+ progress: gr.Progress = PROGRESS,
62
+ ) -> tuple[str, str]:
63
+ page_num = None if page == "(Tất cả trang)" else int(page)
64
+ set_runtime_gemini_api_key(gemini_key)
65
+ progress(0.3, desc="Đang truy xuất ngữ cảnh…")
66
+ try:
67
+ result = summarize(
68
+ query=query.strip() or None,
69
+ k=int(k),
70
+ filters=build_filters(selected_docs, page_num),
71
+ )
72
+ except RuntimeError as error:
73
+ raise _empty_result_error() from error
74
+ progress(0.9, desc="Đang định dạng kết quả…")
75
+ return str(export(result, fmt="md")), result.model_dump_json(indent=2)
76
+
77
+
78
+ def generate_quiz_set(
79
+ query: str,
80
+ count: int,
81
+ k: int,
82
+ selected_docs: list[str],
83
+ page: str,
84
+ gemini_key: str,
85
+ progress: gr.Progress = PROGRESS,
86
+ ) -> tuple[str, str]:
87
+ page_num = None if page == "(Tất cả trang)" else int(page)
88
+ set_runtime_gemini_api_key(gemini_key)
89
+ progress(0.3, desc="Đang truy xuất ngữ cảnh…")
90
+ try:
91
+ result = generate_quiz(
92
+ query=query.strip() or None,
93
+ count=int(count),
94
+ k=int(k),
95
+ filters=build_filters(selected_docs, page_num),
96
+ )
97
+ except RuntimeError as error:
98
+ raise _empty_result_error() from error
99
+ progress(0.9, desc="Đang định dạng kết quả…")
100
+ return str(export(result, fmt="md")), result.model_dump_json(indent=2)
101
+
102
+
103
+ def generate_flashcard_set(
104
+ query: str,
105
+ count: int,
106
+ k: int,
107
+ selected_docs: list[str],
108
+ page: str,
109
+ gemini_key: str,
110
+ progress: gr.Progress = PROGRESS,
111
+ ) -> tuple[str, str]:
112
+ page_num = None if page == "(Tất cả trang)" else int(page)
113
+ set_runtime_gemini_api_key(gemini_key)
114
+ progress(0.3, desc="Đang truy xuất ngữ cảnh…")
115
+ try:
116
+ result = generate_flashcards(
117
+ query=query.strip() or None,
118
+ count=int(count),
119
+ k=int(k),
120
+ filters=build_filters(selected_docs, page_num),
121
+ )
122
+ except RuntimeError as error:
123
+ raise _empty_result_error() from error
124
+ progress(0.9, desc="Đang định dạng kết quả…")
125
+ return str(export(result, fmt="md")), result.model_dump_json(indent=2)
126
+
127
+
128
+ def _empty_result_error() -> gr.Error:
129
+ return gr.Error(
130
+ "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."
131
+ )
src/ui/content.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BRAND_HEADER_HTML = """
2
+ <header class="product-header">
3
+ <a class="brand-lockup" href="#workspace" aria-label="DocuLearn-RAG">
4
+ <span class="brand-mark" aria-hidden="true">
5
+ <svg viewBox="0 0 32 32" role="img">
6
+ <path d="M8 4.5h12.5a3 3 0 0 1 3 3V22H11a3 3 0 0 1-3-3V4.5Z"/>
7
+ <path d="M11.5 8h12a3 3 0 0 1 3 3v16.5H14.5a3 3 0 0 1-3-3V8Z"/>
8
+ <path d="M16 14h6.5M16 18h6.5M16 22h4"/>
9
+ </svg>
10
+ </span>
11
+ <span>DocuLearn-RAG</span>
12
+ </a>
13
+ <div class="header-status">
14
+ <span class="status-dot" aria-hidden="true"></span>
15
+ Local-first workspace
16
+ </div>
17
+ </header>
18
+ <section class="hero-shell">
19
+ <div class="hero-copy">
20
+ <div class="eyebrow">Document intelligence workspace</div>
21
+ <h1>Học sâu hơn từ<br> <span>tài liệu của bạn.</span></h1>
22
+ <p>Biến PDF thành một không gian học có dẫn nguồn — hỏi đáp, tóm tắt,
23
+ quiz và flashcards trên cùng một luồng làm việc.</p>
24
+ </div>
25
+ <div class="hero-visual" aria-hidden="true">
26
+ <div class="document-orbit orbit-one"></div>
27
+ <div class="document-orbit orbit-two"></div>
28
+ <div class="document-stack">
29
+ <div class="document-sheet sheet-back"></div>
30
+ <div class="document-sheet sheet-mid"></div>
31
+ <div class="document-sheet sheet-front">
32
+ <span></span><span></span><span></span><span></span>
33
+ </div>
34
+ <div class="rag-node node-a"></div>
35
+ <div class="rag-node node-b"></div>
36
+ <div class="rag-node node-c"></div>
37
+ </div>
38
+ </div>
39
+ </section>
40
+ """
41
+
42
+ INFO_NOTE_HTML = """
43
+ <div class="workflow-strip">
44
+ <div class="workflow-intro">
45
+ <span class="workflow-label">Bắt đầu</span>
46
+ <strong>Một luồng học, bốn công cụ.</strong>
47
+ </div>
48
+ <ol class="workflow-steps">
49
+ <li><span>01</span>Tải PDF</li>
50
+ <li><span>02</span>Chọn phạm vi</li>
51
+ <li><span>03</span>Nhập Gemini key</li>
52
+ <li><span>04</span>Bắt đầu học</li>
53
+ </ol>
54
+ </div>
55
+ """
56
+
57
+ UPLOAD_HEADING_HTML = """
58
+ <div class="panel-heading">
59
+ <span class="panel-icon" aria-hidden="true">
60
+ <svg viewBox="0 0 24 24"><path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5"/>
61
+ <path d="M5 14v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"/></svg>
62
+ </span>
63
+ <div><h2>Nguồn tài liệu</h2><p>Tải và lập chỉ mục PDF của bạn.</p></div>
64
+ </div>
65
+ """
66
+
67
+ LIBRARY_HEADING_HTML = """
68
+ <div class="panel-heading">
69
+ <span class="panel-icon" aria-hidden="true">
70
+ <svg viewBox="0 0 24 24">
71
+ <path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H11v17H6.5A2.5 2.5 0 0 0 4 22V5.5Z"/>
72
+ <path d="M20 5.5A2.5 2.5 0 0 0 17.5 3H13v17h4.5A2.5 2.5 0 0 1 20 22V5.5Z"/></svg>
73
+ </span>
74
+ <div><h2>Thư viện đã index</h2><p>Chọn tài liệu và phạm vi trước khi truy vấn.</p></div>
75
+ </div>
76
+ """
77
+
78
+ EMPTY_LIBRARY_HTML = """
79
+ <div class="library-empty">
80
+ <span class="library-empty-icon" aria-hidden="true">
81
+ <svg viewBox="0 0 24 24">
82
+ <path d="M7 3.5h7l3 3V20H7a2 2 0 0 1-2-2V5.5a2 2 0 0 1 2-2Z"/>
83
+ <path d="M14 3.5V7h3M8.5 11h5M8.5 14.5h6"/>
84
+ </svg>
85
+ </span>
86
+ <span><strong>Thư viện đang trống</strong>
87
+ <small>Tải PDF ở khung bên trái để bắt đầu không gian học của bạn.</small></span>
88
+ </div>
89
+ """
90
+
91
+ USAGE_MARKDOWN = """
92
+ 1. **Tải PDF** ở khối bên trái rồi bấm **Nạp và index**.
93
+ 2. **Chọn tài liệu** muốn học trong danh sách đã index.
94
+ 3. Dùng các tab để **hỏi đáp**, **tóm tắt**, **tạo quiz** hoặc **flashcards**.
95
+ 4. Nếu chỉ chọn đúng 1 tài liệu, bạn có thể lọc thêm theo **trang**.
96
+
97
+ **Mẹo:** Khi đặt câu hỏi rõ ràng theo chủ đề, kết quả RAG thường sát và dễ học hơn.
98
+ """
src/ui/feature_panel.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import NamedTuple
4
+
5
+ import gradio as gr
6
+
7
+ from src.ui.helpers import result_markdown
8
+
9
+
10
+ class FeaturePanel(NamedTuple):
11
+ query: gr.Textbox
12
+ button: gr.Button
13
+ item_count: gr.Slider | None
14
+ retrieval_count: gr.Slider
15
+ raw: gr.Code
16
+ markdown: gr.Markdown
17
+ download: gr.File
18
+
19
+
20
+ def build_feature_panel(
21
+ *,
22
+ description: str,
23
+ button_label: str,
24
+ retrieval_count: int,
25
+ download_label: str,
26
+ item_count: tuple[int, int, int, str] | None = None,
27
+ ) -> FeaturePanel:
28
+ gr.Markdown(description, elem_classes="feature-sub")
29
+ with gr.Row(equal_height=False, elem_classes="feature-layout"):
30
+ with gr.Column(scale=4, min_width=0, elem_classes="feature-controls"):
31
+ query = gr.Textbox(label="Chủ đề (tuỳ chọn)", lines=1)
32
+ button = gr.Button(
33
+ button_label,
34
+ variant="primary",
35
+ elem_classes="gen-btn",
36
+ )
37
+ with gr.Accordion("Tuỳ chọn nâng cao", open=False):
38
+ item_count_component = None
39
+ if item_count is not None:
40
+ minimum, maximum, value, label = item_count
41
+ item_count_component = gr.Slider(
42
+ minimum,
43
+ maximum,
44
+ value=value,
45
+ step=1,
46
+ label=label,
47
+ )
48
+ k = gr.Slider(
49
+ 1,
50
+ 64,
51
+ value=retrieval_count,
52
+ step=1,
53
+ label="Số đoạn truy xuất (k)",
54
+ )
55
+ with gr.Accordion("JSON debug", open=False):
56
+ raw = gr.Code(label="", language="json", show_label=False)
57
+ with gr.Column(scale=8, min_width=0, elem_classes="feature-output"):
58
+ markdown = result_markdown()
59
+ download = gr.File(label=download_label, interactive=False)
60
+ return FeaturePanel(
61
+ query,
62
+ button,
63
+ item_count_component,
64
+ k,
65
+ raw,
66
+ markdown,
67
+ download,
68
+ )
src/ui/helpers.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ from pathlib import Path
5
+ from uuid import uuid4
6
+
7
+ import gradio as gr
8
+
9
+ from src.config import settings
10
+
11
+ PROJECT_ROOT = Path(__file__).resolve().parents[2]
12
+ CSS = (PROJECT_ROOT / "static" / "style.css").read_text(encoding="utf-8")
13
+ PROGRESS = gr.Progress()
14
+
15
+ THEME = gr.themes.Base().set(
16
+ background_fill_primary="#08090a",
17
+ background_fill_primary_dark="#08090a",
18
+ background_fill_secondary="#0f1012",
19
+ background_fill_secondary_dark="#0f1012",
20
+ block_background_fill="transparent",
21
+ block_background_fill_dark="transparent",
22
+ block_border_color="transparent",
23
+ block_border_color_dark="transparent",
24
+ block_border_width="0px",
25
+ body_background_fill="#08090a",
26
+ body_background_fill_dark="#08090a",
27
+ body_text_color="#f7f8f8",
28
+ body_text_color_dark="#f7f8f8",
29
+ input_background_fill="#17181b",
30
+ input_background_fill_dark="#17181b",
31
+ input_border_color="rgba(255,255,255,.10)",
32
+ input_border_color_dark="rgba(255,255,255,.10)",
33
+ input_placeholder_color="#7c818a",
34
+ input_placeholder_color_dark="#7c818a",
35
+ button_primary_background_fill="#4f5bc0",
36
+ button_primary_background_fill_dark="#4f5bc0",
37
+ button_primary_background_fill_hover="#5a65ca",
38
+ button_primary_background_fill_hover_dark="#5a65ca",
39
+ button_primary_border_color="#7170ff",
40
+ button_primary_border_color_dark="#7170ff",
41
+ button_primary_border_color_hover="#828fff",
42
+ button_primary_border_color_hover_dark="#828fff",
43
+ button_primary_text_color="#f7f8f8",
44
+ button_primary_text_color_dark="#f7f8f8",
45
+ button_primary_text_color_hover="#ffffff",
46
+ button_primary_text_color_hover_dark="#ffffff",
47
+ button_secondary_background_fill="#17181b",
48
+ button_secondary_background_fill_dark="#17181b",
49
+ button_secondary_background_fill_hover="#202126",
50
+ button_secondary_background_fill_hover_dark="#202126",
51
+ button_secondary_border_color="rgba(255,255,255,.10)",
52
+ button_secondary_border_color_dark="rgba(255,255,255,.10)",
53
+ button_secondary_text_color="#c6c9d0",
54
+ button_secondary_text_color_dark="#c6c9d0",
55
+ )
56
+
57
+
58
+ def status_html(message: str, *, trusted: bool = False) -> str:
59
+ body = message if trusted else html.escape(message, quote=False)
60
+ return f'<div class="status-bar">{body}</div>'
61
+
62
+
63
+ def result_markdown() -> gr.Markdown:
64
+ return gr.Markdown(elem_classes="result-markdown")
65
+
66
+
67
+ def select_learning_tab(label: str) -> gr.Tabs:
68
+ tab_ids = {
69
+ "Hỏi đáp": "qa",
70
+ "Tóm tắt": "summary",
71
+ "Quiz": "quiz",
72
+ "Flashcards": "flashcards",
73
+ }
74
+ return gr.Tabs(selected=tab_ids.get(label, "qa"))
75
+
76
+
77
+ def int_value(value: object) -> int:
78
+ if isinstance(value, (int, float, str)):
79
+ return int(value)
80
+ return 0
81
+
82
+
83
+ def write_export(md_text: str, filename: str) -> str | None:
84
+ if not md_text or md_text.startswith("Lỗi:"):
85
+ return None
86
+ stem = Path(filename).stem
87
+ output_path = settings.export_dir / f"{stem}-{uuid4().hex[:12]}.md"
88
+ output_path.parent.mkdir(parents=True, exist_ok=True)
89
+ output_path.write_text(md_text, encoding="utf-8")
90
+ return str(output_path)
src/ui/layout.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import gradio as gr
4
+
5
+ from src.config import settings
6
+ from src.ui.callbacks import (
7
+ ask_chat,
8
+ generate_flashcard_set,
9
+ generate_quiz_set,
10
+ summarize_documents,
11
+ )
12
+ from src.ui.content import (
13
+ BRAND_HEADER_HTML,
14
+ EMPTY_LIBRARY_HTML,
15
+ INFO_NOTE_HTML,
16
+ LIBRARY_HEADING_HTML,
17
+ UPLOAD_HEADING_HTML,
18
+ USAGE_MARKDOWN,
19
+ )
20
+ from src.ui.feature_panel import build_feature_panel
21
+ from src.ui.helpers import select_learning_tab, status_html, write_export
22
+ from src.ui.uploads import pages_for_selection, refresh_docs, upload_pdf
23
+
24
+
25
+ def build_demo() -> gr.Blocks:
26
+ with gr.Blocks(title="DocuLearn-RAG", fill_width=True, fill_height=True) as demo:
27
+ gr.HTML(BRAND_HEADER_HTML, elem_classes="brand-shell")
28
+ gr.HTML(INFO_NOTE_HTML, elem_classes="site-info-note")
29
+ doc_map_state = gr.State({})
30
+
31
+ with gr.Row(equal_height=False, elem_classes="main-layout", elem_id="workspace"):
32
+ with gr.Column(scale=4, min_width=0, elem_classes="control-stack"):
33
+ gr.HTML(UPLOAD_HEADING_HTML)
34
+ upload = gr.File(
35
+ label="Thả PDF vào đây hoặc chọn từ máy",
36
+ show_label=False,
37
+ file_types=[".pdf"],
38
+ file_count="multiple",
39
+ type="filepath",
40
+ elem_classes="upload-dropzone",
41
+ )
42
+ upload_btn = gr.Button(
43
+ "Nạp và index",
44
+ variant="primary",
45
+ elem_classes="gen-btn",
46
+ )
47
+ upload_status = gr.HTML(status_html("Sẵn sàng."))
48
+
49
+ with gr.Accordion("Gemini API key", open=False):
50
+ gr.Markdown(
51
+ "Nhập API key để chạy Gemini. Lấy key tại: "
52
+ "[Google AI Studio](https://aistudio.google.com/app/api-keys). ",
53
+ elem_classes="help-markdown",
54
+ )
55
+ gemini_key_input = gr.Textbox(
56
+ label="Gemini API Key",
57
+ type="password",
58
+ placeholder="AIza...",
59
+ lines=1,
60
+ max_lines=1,
61
+ )
62
+
63
+ with gr.Accordion("Hướng dẫn sử dụng", open=False):
64
+ gr.Markdown(USAGE_MARKDOWN, elem_classes="help-markdown")
65
+
66
+ with gr.Accordion("Thông tin hệ thống", open=False):
67
+ gr.Markdown(
68
+ f"""
69
+ - LLM model: `{settings.llm_model}`
70
+ - Embedding model: `{settings.embedding_model}`
71
+ - Collection: `{settings.qdrant_collection}`
72
+ - Data dir: `{settings.data_dir}`
73
+ - Storage dir: `{settings.storage_dir}`
74
+ """,
75
+ elem_classes="help-markdown",
76
+ )
77
+
78
+ with gr.Column(scale=7, min_width=0, elem_classes="preview-col"):
79
+ gr.HTML(LIBRARY_HEADING_HTML)
80
+ refresh_btn = gr.Button("Làm mới thư viện")
81
+ doc_summary = gr.HTML(EMPTY_LIBRARY_HTML, elem_classes="doc-summary")
82
+ docs = gr.CheckboxGroup(label="Chọn tài liệu", choices=[], value=[])
83
+ page = gr.Dropdown(
84
+ label="Trang (chỉ áp dụng khi chọn đúng 1 tài liệu)",
85
+ choices=["(Tất cả trang)"],
86
+ value="(Tất cả trang)",
87
+ )
88
+ doc_list_md = gr.Markdown("")
89
+
90
+ learning_nav = gr.Radio(
91
+ ["Hỏi đáp", "Tóm tắt", "Quiz", "Flashcards"],
92
+ value="Hỏi đáp",
93
+ label="Công cụ học tập",
94
+ show_label=False,
95
+ elem_classes="learning-nav",
96
+ )
97
+ with gr.Tabs(selected="qa", elem_classes="learning-tabs") as learning_tabs:
98
+ with gr.Tab("Hỏi đáp", id="qa"):
99
+ chatbot = gr.Chatbot(
100
+ elem_classes="qa-chat",
101
+ height=420,
102
+ show_label=False,
103
+ )
104
+ gr.Markdown(
105
+ "Nhập câu hỏi ở ô bên dưới và nhấn **Enter** để chat theo "
106
+ "các tài liệu bạn đã chọn.",
107
+ elem_classes="feature-sub",
108
+ )
109
+ q = gr.Textbox(
110
+ label="",
111
+ show_label=False,
112
+ lines=1,
113
+ placeholder="Nhập câu hỏi và nhấn Enter…",
114
+ elem_classes="qa-input",
115
+ )
116
+ with gr.Accordion("Tuỳ chọn nâng cao", open=False):
117
+ k_ask = gr.Slider(1, 32, value=6, step=1, label="Top-k retrieval")
118
+ with gr.Accordion("JSON debug", open=False):
119
+ ask_raw = gr.Code(label="", language="json", show_label=False)
120
+
121
+ with gr.Tab("Tóm tắt", id="summary"):
122
+ summary_panel = build_feature_panel(
123
+ description=(
124
+ "Tạo tóm tắt theo phạm vi tài liệu đã chọn "
125
+ "(và theo trang nếu bạn chỉ chọn 1 tài liệu)."
126
+ ),
127
+ button_label="Tạo tóm tắt",
128
+ retrieval_count=10,
129
+ download_label="Tải Markdown",
130
+ )
131
+
132
+ with gr.Tab("Quiz", id="quiz"):
133
+ quiz_panel = build_feature_panel(
134
+ description="Tạo bộ câu hỏi trắc nghiệm từ các tài liệu bạn đã chọn.",
135
+ button_label="Tạo quiz",
136
+ retrieval_count=10,
137
+ download_label="Tải Markdown",
138
+ item_count=(1, 30, 3, "Số câu hỏi"),
139
+ )
140
+
141
+ with gr.Tab("Flashcards", id="flashcards"):
142
+ flashcard_panel = build_feature_panel(
143
+ description="Tạo flashcards từ các tài liệu bạn đã chọn để ôn tập nhanh.",
144
+ button_label="Tạo flashcards",
145
+ retrieval_count=16,
146
+ download_label="Tải Markdown",
147
+ item_count=(1, 40, 15, "Số thẻ"),
148
+ )
149
+
150
+ gr.HTML('<div class="footer-text"><span>DocuLearn-RAG</span></div>')
151
+
152
+ learning_nav.change(
153
+ fn=select_learning_tab,
154
+ inputs=[learning_nav],
155
+ outputs=[learning_tabs],
156
+ api_name="select_learning_tab",
157
+ )
158
+ refresh_btn.click(
159
+ fn=refresh_docs,
160
+ inputs=[],
161
+ outputs=[docs, doc_map_state, page, doc_summary, doc_list_md],
162
+ api_name="refresh_documents",
163
+ )
164
+ docs.change(
165
+ fn=pages_for_selection,
166
+ inputs=[doc_map_state, docs],
167
+ outputs=[page],
168
+ api_name="pages_for_selection",
169
+ )
170
+ upload_btn.click(
171
+ fn=upload_pdf,
172
+ inputs=[upload],
173
+ outputs=[upload_status, docs, doc_map_state, page, doc_summary, doc_list_md],
174
+ api_name="upload_pdf",
175
+ )
176
+ q.submit(
177
+ fn=ask_chat,
178
+ inputs=[q, chatbot, k_ask, docs, page, gemini_key_input],
179
+ outputs=[chatbot, ask_raw, q],
180
+ api_name="ask_chat",
181
+ )
182
+ summary_panel.button.click(
183
+ fn=summarize_documents,
184
+ inputs=[
185
+ summary_panel.query,
186
+ summary_panel.retrieval_count,
187
+ docs,
188
+ page,
189
+ gemini_key_input,
190
+ ],
191
+ outputs=[summary_panel.markdown, summary_panel.raw],
192
+ api_name="summarize_documents",
193
+ ).then(
194
+ fn=lambda text: write_export(text, "summary.md"),
195
+ inputs=[summary_panel.markdown],
196
+ outputs=[summary_panel.download],
197
+ )
198
+ assert quiz_panel.item_count is not None
199
+ quiz_panel.button.click(
200
+ fn=generate_quiz_set,
201
+ inputs=[
202
+ quiz_panel.query,
203
+ quiz_panel.item_count,
204
+ quiz_panel.retrieval_count,
205
+ docs,
206
+ page,
207
+ gemini_key_input,
208
+ ],
209
+ outputs=[quiz_panel.markdown, quiz_panel.raw],
210
+ api_name="generate_quiz_set",
211
+ ).then(
212
+ fn=lambda text: write_export(text, "quiz.md"),
213
+ inputs=[quiz_panel.markdown],
214
+ outputs=[quiz_panel.download],
215
+ )
216
+ assert flashcard_panel.item_count is not None
217
+ flashcard_panel.button.click(
218
+ fn=generate_flashcard_set,
219
+ inputs=[
220
+ flashcard_panel.query,
221
+ flashcard_panel.item_count,
222
+ flashcard_panel.retrieval_count,
223
+ docs,
224
+ page,
225
+ gemini_key_input,
226
+ ],
227
+ outputs=[flashcard_panel.markdown, flashcard_panel.raw],
228
+ api_name="generate_flashcard_set",
229
+ ).then(
230
+ fn=lambda text: write_export(text, "flashcards.md"),
231
+ inputs=[flashcard_panel.markdown],
232
+ outputs=[flashcard_panel.download],
233
+ )
234
+
235
+ return demo
src/ui/runtime.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import gradio as gr
4
+
5
+ from src.config import settings
6
+ from src.ui.helpers import CSS, THEME
7
+
8
+
9
+ def launch_demo(demo: gr.Blocks) -> None:
10
+ settings.export_dir.mkdir(parents=True, exist_ok=True)
11
+ auth = None
12
+ if settings.gradio_username and settings.gradio_password:
13
+ auth = (settings.gradio_username, settings.gradio_password)
14
+ demo.queue(default_concurrency_limit=2).launch(
15
+ allowed_paths=[str(settings.export_dir.resolve())],
16
+ auth=auth,
17
+ css=CSS,
18
+ max_file_size=settings.max_upload_bytes,
19
+ server_name=settings.server_name,
20
+ server_port=settings.server_port,
21
+ theme=THEME,
22
+ )
src/ui/uploads.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import gradio as gr
8
+
9
+ from src.export import safe_markdown_code
10
+ from src.filters import MetadataFilter, filters_to_dict
11
+ from src.indexing import save_and_ingest_pdf
12
+ from src.store import list_documents
13
+ from src.ui.content import EMPTY_LIBRARY_HTML
14
+ from src.ui.helpers import int_value, status_html
15
+
16
+
17
+ def read_uploaded_pdf(file_obj: object) -> tuple[bytes, str]:
18
+ if isinstance(file_obj, str):
19
+ path = Path(file_obj)
20
+ return path.read_bytes(), path.name
21
+
22
+ raw_path = getattr(file_obj, "path", None)
23
+ raw_name = getattr(file_obj, "orig_name", None)
24
+ if isinstance(raw_path, str) and raw_path:
25
+ path = Path(raw_path)
26
+ name = raw_name.strip() if isinstance(raw_name, str) and raw_name.strip() else path.name
27
+ return path.read_bytes(), name
28
+
29
+ if isinstance(file_obj, dict):
30
+ raw_path = file_obj.get("path")
31
+ raw_name = file_obj.get("orig_name") or file_obj.get("name")
32
+ if isinstance(raw_path, str) and raw_path:
33
+ path = Path(raw_path)
34
+ name = raw_name.strip() if isinstance(raw_name, str) and raw_name.strip() else path.name
35
+ return path.read_bytes(), name
36
+
37
+ raise TypeError(f"Unsupported uploaded file type: {type(file_obj).__name__}")
38
+
39
+
40
+ def read_uploaded_pdfs(file_obj: object) -> list[tuple[bytes, str]]:
41
+ if file_obj is None:
42
+ return []
43
+ if isinstance(file_obj, (list, tuple)):
44
+ return [read_uploaded_pdf(item) for item in file_obj]
45
+ return [read_uploaded_pdf(file_obj)]
46
+
47
+
48
+ def build_filters(filenames: list[str] | None, page: int | None) -> dict[str, object] | None:
49
+ payload: dict[str, object] = {}
50
+ if filenames:
51
+ payload["filenames"] = filenames
52
+ if page is not None:
53
+ payload["page"] = page
54
+ return filters_to_dict(MetadataFilter.model_validate(payload)) if payload else None
55
+
56
+
57
+ def refresh_docs() -> tuple[
58
+ dict[str, Any],
59
+ dict[str, dict[str, object]],
60
+ dict[str, Any],
61
+ str,
62
+ str,
63
+ ]:
64
+ docs = list_documents()
65
+ choices = [str(doc["filename"]) for doc in docs]
66
+ doc_map = {str(doc["filename"]): doc for doc in docs}
67
+ if docs:
68
+ summary = (
69
+ '<div class="library-stats">'
70
+ f"<strong>{len(docs)}</strong> tài liệu đã index"
71
+ '<span aria-hidden="true">·</span>'
72
+ f"<strong>{sum(int_value(doc['chunk_count']) for doc in docs)}</strong> đoạn văn"
73
+ "</div>"
74
+ )
75
+ else:
76
+ summary = EMPTY_LIBRARY_HTML
77
+ filenames_text = (
78
+ "\n".join(f"- {safe_markdown_code(name)}" for name in choices) if choices else ""
79
+ )
80
+ return (
81
+ gr.update(choices=choices, value=[]),
82
+ doc_map,
83
+ gr.update(
84
+ choices=["(Tất cả trang)"],
85
+ value="(Tất cả trang)",
86
+ interactive=bool(docs),
87
+ ),
88
+ summary,
89
+ filenames_text,
90
+ )
91
+
92
+
93
+ def pages_for_selection(doc_map: dict[str, Any], selected: list[str]) -> dict[str, Any]:
94
+ if len(selected) != 1:
95
+ return gr.update(
96
+ choices=["(Tất cả trang)"],
97
+ value="(Tất cả trang)",
98
+ interactive=False,
99
+ )
100
+ doc = doc_map.get(selected[0]) or {}
101
+ raw_pages = doc.get("pages")
102
+ pages = raw_pages if isinstance(raw_pages, list) else []
103
+ page_choices = ["(Tất cả trang)", *[str(page) for page in pages]]
104
+ return gr.update(
105
+ choices=page_choices,
106
+ value="(Tất cả trang)",
107
+ interactive=True,
108
+ )
109
+
110
+
111
+ def upload_pdf(
112
+ file: object | None,
113
+ ) -> tuple[str, dict[str, Any], dict[str, dict[str, object]], dict[str, Any], str, str]:
114
+ payloads = read_uploaded_pdfs(file)
115
+ if not payloads:
116
+ choices, doc_map, page_dropdown, summary, filenames_text = refresh_docs()
117
+ return (
118
+ status_html("Vui lòng chọn ít nhất một file PDF."),
119
+ choices,
120
+ doc_map,
121
+ page_dropdown,
122
+ summary,
123
+ filenames_text,
124
+ )
125
+
126
+ successes: list[str] = []
127
+ failures: list[str] = []
128
+ chunks_total = 0
129
+ for file_bytes, filename in payloads:
130
+ try:
131
+ info = save_and_ingest_pdf(file_bytes, filename)
132
+ except (OSError, RuntimeError, TypeError, ValueError) as error:
133
+ failures.append(f"{filename}: {error}")
134
+ continue
135
+ successes.append(str(info["filename"]))
136
+ chunks_total += int_value(info.get("chunks_indexed"))
137
+
138
+ parts: list[str] = []
139
+ if successes:
140
+ parts.append(f"Đã nạp {len(successes)} file · {chunks_total} đoạn")
141
+ if failures:
142
+ parts.append(f"Không thể nạp {len(failures)} file")
143
+ details = ""
144
+ if failures:
145
+ items = "".join(
146
+ f"<li><code>{html.escape(item, quote=False)}</code></li>" for item in failures
147
+ )
148
+ details = f"<details><summary>Xem lỗi</summary><ul>{items}</ul></details>"
149
+ body = (" · ".join(parts) if parts else "Không có file hợp lệ.") + details
150
+
151
+ choices, doc_map, page_dropdown, summary, filenames_text = refresh_docs()
152
+ return (
153
+ status_html(body, trusted=True),
154
+ choices,
155
+ doc_map,
156
+ page_dropdown,
157
+ summary,
158
+ filenames_text,
159
+ )
static/style.css ADDED
@@ -0,0 +1,1148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap");
2
+
3
+ :root,
4
+ :root.dark,
5
+ .dark,
6
+ .gradio-container {
7
+ color-scheme: dark;
8
+ --font-sans: "Inter Variable", "Inter", "SF Pro Display", -apple-system,
9
+ BlinkMacSystemFont, "Segoe UI", sans-serif;
10
+ --font-mono: "Berkeley Mono", "SFMono-Regular", Menlo, monospace;
11
+
12
+ --surface-canvas: #08090a;
13
+ --surface-deep: #050506;
14
+ --surface-panel: #0f1012;
15
+ --surface-elevated: #17181b;
16
+ --surface-hover: #202126;
17
+ --surface-glass: rgba(15, 16, 18, 0.78);
18
+ --surface-input: rgba(255, 255, 255, 0.035);
19
+
20
+ --text-primary: #f7f8f8;
21
+ --text-secondary: #c6c9d0;
22
+ --text-tertiary: #8a8f98;
23
+ --text-disabled: #7c818a;
24
+
25
+ --border-subtle: rgba(255, 255, 255, 0.06);
26
+ --border-default: rgba(255, 255, 255, 0.1);
27
+ --border-strong: rgba(255, 255, 255, 0.16);
28
+ --grid-line: rgba(255, 255, 255, 0.025);
29
+
30
+ --accent-primary: #5e6ad2;
31
+ --accent-bright: #7170ff;
32
+ --accent-hover: #828fff;
33
+ --action-primary: #4f5bc0;
34
+ --action-hover: #5a65ca;
35
+ --accent-wash: rgba(113, 112, 255, 0.12);
36
+ --accent-glow: rgba(94, 106, 210, 0.2);
37
+
38
+ --status-success: #36b37e;
39
+ --status-warning: #d5a83f;
40
+ --status-error: #e0626c;
41
+
42
+ --space-1: 4px;
43
+ --space-2: 8px;
44
+ --space-3: 12px;
45
+ --space-4: 16px;
46
+ --space-5: 20px;
47
+ --space-6: 24px;
48
+ --space-8: 32px;
49
+ --space-10: 40px;
50
+ --space-12: 48px;
51
+ --space-16: 64px;
52
+
53
+ --radius-control: 7px;
54
+ --radius-card: 12px;
55
+ --radius-panel: 16px;
56
+ --radius-round: 999px;
57
+ --content-max: 1280px;
58
+
59
+ --background-fill-primary: var(--surface-canvas);
60
+ --background-fill-secondary: var(--surface-panel);
61
+ --body-background-fill: var(--surface-canvas);
62
+ --body-text-color: var(--text-primary);
63
+ --block-background-fill: transparent;
64
+ --block-border-color: transparent;
65
+ --block-border-width: 0;
66
+ --input-background-fill: var(--surface-elevated);
67
+ --input-border-color: var(--border-default);
68
+ --input-placeholder-color: var(--text-disabled);
69
+ --button-secondary-background-fill: var(--surface-elevated);
70
+ --button-secondary-text-color: var(--text-secondary);
71
+ --button-secondary-border-color: var(--border-default);
72
+ }
73
+
74
+ * {
75
+ box-sizing: border-box;
76
+ }
77
+
78
+ html {
79
+ scroll-behavior: smooth;
80
+ background: var(--surface-canvas);
81
+ }
82
+
83
+ html,
84
+ body {
85
+ min-height: 100%;
86
+ margin: 0;
87
+ font-family: var(--font-sans) !important;
88
+ font-feature-settings: "cv01" 1, "ss03" 1;
89
+ color: var(--text-primary) !important;
90
+ background-color: var(--surface-canvas) !important;
91
+ }
92
+
93
+ body {
94
+ background-image:
95
+ radial-gradient(circle at 77% 10%, var(--accent-glow), transparent 29rem),
96
+ radial-gradient(circle at 14% 22%, var(--accent-wash), transparent 23rem),
97
+ linear-gradient(var(--grid-line) 1px, transparent 1px),
98
+ linear-gradient(90deg, var(--grid-line) 1px, transparent 1px) !important;
99
+ background-size: auto, auto, 48px 48px, 48px 48px !important;
100
+ background-attachment: fixed !important;
101
+ }
102
+
103
+ .gradio-container,
104
+ .gradio-container .main,
105
+ .gradio-container .contain,
106
+ .gradio-container .html-container,
107
+ .gradio-container .prose {
108
+ color: var(--text-primary) !important;
109
+ background: transparent !important;
110
+ }
111
+
112
+ .gradio-container {
113
+ width: min(100%, var(--content-max)) !important;
114
+ max-width: var(--content-max) !important;
115
+ margin: 0 auto !important;
116
+ padding: 0 clamp(var(--space-4), 3vw, var(--space-8)) var(--space-8) !important;
117
+ }
118
+
119
+ .gradio-container .block,
120
+ .gradio-container .form,
121
+ .gradio-container .panel,
122
+ .gradio-container .wrap,
123
+ .gradio-container fieldset {
124
+ color: var(--text-primary) !important;
125
+ }
126
+
127
+ /* Brand navigation */
128
+ .brand-shell {
129
+ position: relative;
130
+ z-index: 2;
131
+ }
132
+
133
+ .product-header {
134
+ display: flex;
135
+ align-items: center;
136
+ justify-content: space-between;
137
+ min-height: 68px;
138
+ border-bottom: 1px solid var(--border-subtle);
139
+ }
140
+
141
+ .brand-lockup {
142
+ display: inline-flex;
143
+ align-items: center;
144
+ gap: var(--space-3);
145
+ color: var(--text-primary) !important;
146
+ font-size: 0.9375rem;
147
+ font-weight: 590;
148
+ letter-spacing: -0.012em;
149
+ text-decoration: none !important;
150
+ }
151
+
152
+ .brand-mark {
153
+ display: grid;
154
+ width: 32px;
155
+ height: 32px;
156
+ place-items: center;
157
+ border: 1px solid var(--border-default);
158
+ border-radius: 9px;
159
+ background:
160
+ linear-gradient(145deg, var(--accent-wash), transparent),
161
+ var(--surface-elevated);
162
+ }
163
+
164
+ .brand-mark svg {
165
+ width: 22px;
166
+ height: 22px;
167
+ fill: none;
168
+ stroke: var(--text-primary);
169
+ stroke-linecap: round;
170
+ stroke-linejoin: round;
171
+ stroke-width: 1.5;
172
+ }
173
+
174
+ .brand-mark svg path:first-child {
175
+ fill: var(--accent-primary);
176
+ stroke: var(--accent-hover);
177
+ opacity: 0.55;
178
+ }
179
+
180
+ .header-status {
181
+ display: inline-flex;
182
+ align-items: center;
183
+ gap: var(--space-2);
184
+ color: var(--text-tertiary);
185
+ font-family: var(--font-mono);
186
+ font-size: 0.75rem;
187
+ }
188
+
189
+ .status-dot {
190
+ width: 7px;
191
+ height: 7px;
192
+ border-radius: 50%;
193
+ background: var(--status-success);
194
+ box-shadow: 0 0 0 4px rgba(54, 179, 126, 0.1);
195
+ }
196
+
197
+ /* Hero */
198
+ .hero-shell {
199
+ display: grid;
200
+ grid-template-columns: minmax(0, 1.25fr) minmax(16rem, 0.75fr);
201
+ gap: var(--space-10);
202
+ align-items: center;
203
+ min-height: 410px;
204
+ padding: var(--space-16) 0 var(--space-12);
205
+ }
206
+
207
+ .hero-copy {
208
+ max-width: 48rem;
209
+ }
210
+
211
+ .eyebrow {
212
+ margin-bottom: var(--space-5);
213
+ color: var(--accent-hover);
214
+ font-family: var(--font-mono);
215
+ font-size: 0.75rem;
216
+ font-weight: 510;
217
+ letter-spacing: 0.075em;
218
+ text-transform: uppercase;
219
+ }
220
+
221
+ .hero-copy h1 {
222
+ margin: 0;
223
+ color: var(--text-primary) !important;
224
+ font-size: clamp(2.5rem, 5.6vw, 4.5rem);
225
+ font-weight: 510;
226
+ letter-spacing: -0.045em;
227
+ line-height: 1.02;
228
+ text-wrap: balance;
229
+ }
230
+
231
+ .hero-copy h1 span {
232
+ color: var(--text-tertiary);
233
+ }
234
+
235
+ .hero-copy p {
236
+ max-width: 39rem;
237
+ margin: var(--space-6) 0 0;
238
+ color: var(--text-secondary) !important;
239
+ font-size: 1.0625rem;
240
+ line-height: 1.65;
241
+ text-wrap: pretty;
242
+ }
243
+
244
+ .hero-visual {
245
+ position: relative;
246
+ display: grid;
247
+ min-height: 280px;
248
+ place-items: center;
249
+ isolation: isolate;
250
+ }
251
+
252
+ .hero-visual::before {
253
+ position: absolute;
254
+ z-index: -2;
255
+ width: 240px;
256
+ height: 240px;
257
+ border-radius: 50%;
258
+ background: var(--accent-primary);
259
+ content: "";
260
+ filter: blur(95px);
261
+ opacity: 0.2;
262
+ }
263
+
264
+ .document-orbit {
265
+ position: absolute;
266
+ border: 1px solid var(--border-subtle);
267
+ border-radius: 50%;
268
+ }
269
+
270
+ .orbit-one {
271
+ width: 250px;
272
+ height: 250px;
273
+ }
274
+
275
+ .orbit-two {
276
+ width: 190px;
277
+ height: 190px;
278
+ }
279
+
280
+ .document-stack {
281
+ position: relative;
282
+ width: 164px;
283
+ height: 204px;
284
+ transform: rotate(4deg);
285
+ }
286
+
287
+ .document-sheet {
288
+ position: absolute;
289
+ inset: 0;
290
+ border: 1px solid var(--border-default);
291
+ border-radius: var(--radius-card);
292
+ }
293
+
294
+ .sheet-back {
295
+ background: var(--surface-hover);
296
+ transform: translate(-24px, 17px) rotate(-9deg);
297
+ }
298
+
299
+ .sheet-mid {
300
+ background: var(--accent-primary);
301
+ transform: translate(17px, 9px) rotate(7deg);
302
+ opacity: 0.72;
303
+ }
304
+
305
+ .sheet-front {
306
+ display: flex;
307
+ flex-direction: column;
308
+ gap: var(--space-3);
309
+ padding: var(--space-8) var(--space-6);
310
+ background:
311
+ linear-gradient(145deg, rgba(255, 255, 255, 0.05), transparent 42%),
312
+ var(--surface-elevated);
313
+ box-shadow:
314
+ 0 24px 80px rgba(0, 0, 0, 0.35),
315
+ inset 0 1px 0 var(--border-subtle);
316
+ }
317
+
318
+ .sheet-front::before {
319
+ width: 42px;
320
+ height: 42px;
321
+ margin-bottom: var(--space-3);
322
+ border-radius: 9px;
323
+ background: var(--accent-wash);
324
+ box-shadow: inset 0 0 0 1px var(--border-default);
325
+ content: "";
326
+ }
327
+
328
+ .sheet-front span {
329
+ display: block;
330
+ width: 100%;
331
+ height: 5px;
332
+ border-radius: var(--radius-round);
333
+ background: var(--border-strong);
334
+ }
335
+
336
+ .sheet-front span:nth-child(3) {
337
+ width: 74%;
338
+ }
339
+
340
+ .sheet-front span:nth-child(4) {
341
+ width: 88%;
342
+ }
343
+
344
+ .sheet-front span:nth-child(5) {
345
+ width: 58%;
346
+ }
347
+
348
+ .rag-node {
349
+ position: absolute;
350
+ width: 10px;
351
+ height: 10px;
352
+ border: 2px solid var(--surface-canvas);
353
+ border-radius: 50%;
354
+ background: var(--accent-hover);
355
+ box-shadow: 0 0 18px var(--accent-hover);
356
+ }
357
+
358
+ .node-a {
359
+ top: 11px;
360
+ right: -39px;
361
+ }
362
+
363
+ .node-b {
364
+ right: -31px;
365
+ bottom: 34px;
366
+ }
367
+
368
+ .node-c {
369
+ bottom: -24px;
370
+ left: 24px;
371
+ }
372
+
373
+ /* Workflow strip */
374
+ .site-info-note {
375
+ margin-bottom: var(--space-8) !important;
376
+ }
377
+
378
+ .workflow-strip {
379
+ display: grid;
380
+ grid-template-columns: minmax(13rem, 0.75fr) minmax(0, 2fr);
381
+ gap: var(--space-6);
382
+ align-items: center;
383
+ padding: var(--space-5) var(--space-6);
384
+ border: 1px solid var(--border-subtle);
385
+ border-radius: var(--radius-panel);
386
+ background: var(--surface-glass);
387
+ backdrop-filter: blur(18px);
388
+ }
389
+
390
+ .workflow-intro {
391
+ display: flex;
392
+ flex-direction: column;
393
+ gap: var(--space-1);
394
+ }
395
+
396
+ .workflow-label {
397
+ color: var(--status-warning);
398
+ font-family: var(--font-mono);
399
+ font-size: 0.75rem;
400
+ letter-spacing: 0.06em;
401
+ text-transform: uppercase;
402
+ }
403
+
404
+ .workflow-intro strong {
405
+ color: var(--text-primary);
406
+ font-size: 0.9375rem;
407
+ font-weight: 510;
408
+ }
409
+
410
+ .workflow-steps {
411
+ display: grid;
412
+ grid-template-columns: repeat(4, minmax(0, 1fr));
413
+ gap: var(--space-2);
414
+ margin: 0;
415
+ padding: 0;
416
+ list-style: none;
417
+ }
418
+
419
+ .workflow-steps li {
420
+ display: flex;
421
+ align-items: center;
422
+ gap: var(--space-2);
423
+ min-width: 0;
424
+ color: var(--text-secondary);
425
+ font-size: 0.8125rem;
426
+ white-space: nowrap;
427
+ }
428
+
429
+ .workflow-steps span {
430
+ color: var(--text-disabled);
431
+ font-family: var(--font-mono);
432
+ font-size: 0.6875rem;
433
+ }
434
+
435
+ /* Main workspace */
436
+ .main-layout {
437
+ display: grid !important;
438
+ grid-template-columns: minmax(18rem, 23rem) minmax(0, 1fr) !important;
439
+ gap: var(--space-6) !important;
440
+ align-items: stretch !important;
441
+ margin-bottom: var(--space-8) !important;
442
+ background: transparent !important;
443
+ }
444
+
445
+ .main-layout > .control-stack,
446
+ .main-layout > .preview-col {
447
+ min-width: 0 !important;
448
+ }
449
+
450
+ .control-stack,
451
+ .preview-col {
452
+ display: flex !important;
453
+ overflow: hidden;
454
+ flex-direction: column !important;
455
+ gap: var(--space-4) !important;
456
+ padding: var(--space-6) !important;
457
+ border: 1px solid var(--border-subtle) !important;
458
+ border-radius: var(--radius-panel) !important;
459
+ background:
460
+ linear-gradient(145deg, rgba(255, 255, 255, 0.018), transparent 45%),
461
+ var(--surface-glass) !important;
462
+ box-shadow: inset 0 1px 0 var(--border-subtle) !important;
463
+ backdrop-filter: blur(18px);
464
+ }
465
+
466
+ .panel-heading {
467
+ display: flex;
468
+ align-items: flex-start;
469
+ gap: var(--space-3);
470
+ }
471
+
472
+ .panel-icon {
473
+ display: grid;
474
+ flex: 0 0 36px;
475
+ width: 36px;
476
+ height: 36px;
477
+ place-items: center;
478
+ border: 1px solid var(--border-default);
479
+ border-radius: 9px;
480
+ background: var(--surface-elevated);
481
+ color: var(--accent-hover);
482
+ }
483
+
484
+ .panel-icon svg {
485
+ width: 19px;
486
+ height: 19px;
487
+ fill: none;
488
+ stroke: currentColor;
489
+ stroke-linecap: round;
490
+ stroke-linejoin: round;
491
+ stroke-width: 1.7;
492
+ }
493
+
494
+ .panel-heading h2 {
495
+ margin: 0;
496
+ color: var(--text-primary) !important;
497
+ font-size: 1.125rem;
498
+ font-weight: 590;
499
+ letter-spacing: -0.012em;
500
+ line-height: 1.35;
501
+ }
502
+
503
+ .panel-heading p {
504
+ margin: var(--space-1) 0 0;
505
+ color: var(--text-tertiary) !important;
506
+ font-size: 0.8125rem;
507
+ line-height: 1.45;
508
+ }
509
+
510
+ /* Typography bridge */
511
+ .gradio-container label,
512
+ .gradio-container .gr-label,
513
+ .gradio-container .block-title,
514
+ .gradio-container .label-wrap span,
515
+ .gradio-container .label-wrap {
516
+ color: var(--text-secondary) !important;
517
+ font-size: 0.8125rem !important;
518
+ font-weight: 510 !important;
519
+ }
520
+
521
+ .gradio-container p,
522
+ .gradio-container li,
523
+ .gradio-container .prose {
524
+ color: var(--text-secondary);
525
+ }
526
+
527
+ .gradio-container a {
528
+ color: var(--accent-hover);
529
+ }
530
+
531
+ .gradio-container code {
532
+ color: var(--text-secondary) !important;
533
+ font-family: var(--font-mono) !important;
534
+ }
535
+
536
+ .help-markdown p,
537
+ .help-markdown li,
538
+ .doc-summary,
539
+ .doc-summary p,
540
+ .doc-summary li,
541
+ .feature-sub p {
542
+ color: var(--text-tertiary) !important;
543
+ font-size: 0.875rem !important;
544
+ line-height: 1.6 !important;
545
+ }
546
+
547
+ .doc-summary {
548
+ padding: var(--space-3) var(--space-4) !important;
549
+ border: 1px solid var(--border-subtle);
550
+ border-radius: var(--radius-control);
551
+ background: var(--surface-input) !important;
552
+ }
553
+
554
+ .library-empty {
555
+ display: flex;
556
+ align-items: center;
557
+ gap: var(--space-3);
558
+ }
559
+
560
+ .library-empty-icon {
561
+ display: grid;
562
+ flex: 0 0 36px;
563
+ width: 36px;
564
+ height: 36px;
565
+ place-items: center;
566
+ border: 1px solid var(--border-default);
567
+ border-radius: 9px;
568
+ background: var(--surface-elevated);
569
+ color: var(--text-tertiary);
570
+ }
571
+
572
+ .library-empty-icon svg {
573
+ width: 18px;
574
+ height: 18px;
575
+ fill: none;
576
+ stroke: currentColor;
577
+ stroke-linecap: round;
578
+ stroke-linejoin: round;
579
+ stroke-width: 1.6;
580
+ }
581
+
582
+ .library-empty strong,
583
+ .library-empty small {
584
+ display: block;
585
+ }
586
+
587
+ .library-empty strong {
588
+ color: var(--text-secondary);
589
+ font-size: 0.875rem;
590
+ font-weight: 590;
591
+ }
592
+
593
+ .library-empty small {
594
+ margin-top: 2px;
595
+ color: var(--text-tertiary);
596
+ font-size: 0.75rem;
597
+ line-height: 1.45;
598
+ }
599
+
600
+ .library-stats {
601
+ display: flex;
602
+ flex-wrap: wrap;
603
+ gap: var(--space-2);
604
+ color: var(--text-tertiary);
605
+ font-size: 0.8125rem;
606
+ }
607
+
608
+ .library-stats strong {
609
+ color: var(--text-primary);
610
+ font-weight: 590;
611
+ }
612
+
613
+ /* Inputs and generated Gradio wrappers */
614
+ .gradio-container textarea,
615
+ .gradio-container input:not([type="range"]):not([type="checkbox"]),
616
+ .gradio-container select {
617
+ min-height: 44px !important;
618
+ border: 1px solid var(--border-default) !important;
619
+ border-radius: var(--radius-control) !important;
620
+ outline: none !important;
621
+ background: var(--surface-input) !important;
622
+ box-shadow: none !important;
623
+ color: var(--text-primary) !important;
624
+ font-family: var(--font-sans) !important;
625
+ font-size: 0.9375rem !important;
626
+ font-weight: 400 !important;
627
+ transition:
628
+ background 140ms ease-out,
629
+ border-color 140ms ease-out,
630
+ box-shadow 140ms ease-out !important;
631
+ }
632
+
633
+ .gradio-container textarea:hover,
634
+ .gradio-container input:not([type="range"]):not([type="checkbox"]):hover,
635
+ .gradio-container select:hover {
636
+ border-color: var(--border-strong) !important;
637
+ background: rgba(255, 255, 255, 0.05) !important;
638
+ }
639
+
640
+ .gradio-container textarea:focus,
641
+ .gradio-container input:not([type="range"]):not([type="checkbox"]):focus,
642
+ .gradio-container select:focus {
643
+ border-color: var(--accent-bright) !important;
644
+ box-shadow: 0 0 0 3px var(--accent-wash) !important;
645
+ }
646
+
647
+ .gradio-container ::placeholder {
648
+ color: var(--text-disabled) !important;
649
+ opacity: 1 !important;
650
+ }
651
+
652
+ .gradio-container input[type="checkbox"] {
653
+ accent-color: var(--accent-bright);
654
+ }
655
+
656
+ .gradio-container input[type="range"] {
657
+ accent-color: var(--accent-bright);
658
+ }
659
+
660
+ .gradio-container fieldset,
661
+ .gradio-container form,
662
+ .gradio-container .fieldset,
663
+ .gradio-container .form,
664
+ .gradio-container .gr-form,
665
+ .gradio-container .panel,
666
+ .gradio-container .gr-panel,
667
+ .gradio-container .wrap {
668
+ border-color: var(--border-subtle) !important;
669
+ background: transparent !important;
670
+ }
671
+
672
+ .gradio-container form,
673
+ .gradio-container div.form {
674
+ border: 1px solid var(--border-subtle) !important;
675
+ border-radius: var(--radius-control) !important;
676
+ background: var(--surface-input) !important;
677
+ }
678
+
679
+ .gradio-container .gr-dropdown,
680
+ .gradio-container .gr-checkboxgroup,
681
+ .gradio-container .gr-radiogroup,
682
+ .gradio-container .gr-slider,
683
+ .gradio-container .gr-text-input,
684
+ .gradio-container .gr-textbox,
685
+ .gradio-container .gr-code {
686
+ border-color: transparent !important;
687
+ background: transparent !important;
688
+ }
689
+
690
+ /* File drop area */
691
+ .control-stack .gr-file,
692
+ .upload-dropzone {
693
+ overflow: hidden;
694
+ min-height: 188px;
695
+ border: 1px dashed var(--border-strong) !important;
696
+ border-radius: var(--radius-card) !important;
697
+ background:
698
+ radial-gradient(circle at 50% 0, var(--accent-wash), transparent 60%),
699
+ var(--surface-input) !important;
700
+ box-shadow: inset 0 1px 0 var(--border-subtle) !important;
701
+ }
702
+
703
+ .control-stack .gr-file button,
704
+ .control-stack .gr-file button:not(.gen-btn),
705
+ .upload-dropzone button {
706
+ min-height: 188px !important;
707
+ border: 0 !important;
708
+ background: transparent !important;
709
+ color: var(--text-tertiary) !important;
710
+ font-size: 0 !important;
711
+ }
712
+
713
+ .control-stack .gr-file button:hover,
714
+ .upload-dropzone button:hover {
715
+ color: var(--text-primary) !important;
716
+ background: var(--accent-wash) !important;
717
+ }
718
+
719
+ .control-stack .gr-file button::after,
720
+ .upload-dropzone button::after {
721
+ color: var(--text-secondary);
722
+ content: "Thả PDF vào đây\A hoặc bấm để chọn";
723
+ font-family: var(--font-sans);
724
+ font-size: 0.875rem;
725
+ line-height: 1.65;
726
+ white-space: pre;
727
+ }
728
+
729
+ .upload-dropzone button > * {
730
+ display: none !important;
731
+ }
732
+
733
+ /* Buttons */
734
+ .gradio-container button {
735
+ min-height: 44px !important;
736
+ border: 1px solid var(--border-default) !important;
737
+ border-radius: var(--radius-control) !important;
738
+ background: var(--surface-input) !important;
739
+ box-shadow: inset 0 1px 0 var(--border-subtle) !important;
740
+ color: var(--text-secondary) !important;
741
+ font-family: var(--font-sans) !important;
742
+ font-size: 0.875rem !important;
743
+ font-weight: 510 !important;
744
+ transition:
745
+ transform 140ms ease-out,
746
+ background 140ms ease-out,
747
+ border-color 140ms ease-out,
748
+ color 140ms ease-out !important;
749
+ }
750
+
751
+ .gradio-container button:hover:not(:disabled) {
752
+ border-color: var(--border-strong) !important;
753
+ background: var(--surface-hover) !important;
754
+ color: var(--text-primary) !important;
755
+ }
756
+
757
+ .gradio-container button:active:not(:disabled) {
758
+ transform: translateY(1px) scale(0.995) !important;
759
+ }
760
+
761
+ .gradio-container button:focus-visible,
762
+ .gradio-container a:focus-visible,
763
+ .gradio-container summary:focus-visible {
764
+ outline: 2px solid var(--accent-hover) !important;
765
+ outline-offset: 2px !important;
766
+ }
767
+
768
+ .gradio-container button:disabled {
769
+ border-color: var(--border-subtle) !important;
770
+ color: var(--text-disabled) !important;
771
+ opacity: 0.6;
772
+ }
773
+
774
+ .gradio-container .gen-btn {
775
+ border-color: var(--accent-bright) !important;
776
+ background:
777
+ linear-gradient(180deg, rgba(255, 255, 255, 0.08), transparent),
778
+ var(--action-primary) !important;
779
+ box-shadow:
780
+ inset 0 1px 0 rgba(255, 255, 255, 0.16),
781
+ 0 8px 24px rgba(94, 106, 210, 0.18) !important;
782
+ color: var(--text-primary) !important;
783
+ }
784
+
785
+ .gradio-container .gen-btn:hover:not(:disabled) {
786
+ border-color: var(--accent-hover) !important;
787
+ background:
788
+ linear-gradient(180deg, rgba(255, 255, 255, 0.1), transparent),
789
+ var(--action-hover) !important;
790
+ transform: translateY(-1px) !important;
791
+ }
792
+
793
+ /* Accordions */
794
+ .gradio-container .accordion,
795
+ .gradio-container .gr-accordion {
796
+ overflow: hidden !important;
797
+ border: 1px solid var(--border-subtle) !important;
798
+ border-radius: var(--radius-control) !important;
799
+ background: var(--surface-input) !important;
800
+ }
801
+
802
+ .gradio-container .accordion > .label-wrap,
803
+ .gradio-container .gr-accordion > .label-wrap {
804
+ min-height: 44px;
805
+ padding: 0 var(--space-3) !important;
806
+ background: transparent !important;
807
+ color: var(--text-secondary) !important;
808
+ }
809
+
810
+ .gradio-container .accordion > .label-wrap:hover,
811
+ .gradio-container .gr-accordion > .label-wrap:hover {
812
+ background: var(--surface-hover) !important;
813
+ color: var(--text-primary) !important;
814
+ }
815
+
816
+ /* Status */
817
+ .status-bar {
818
+ position: relative;
819
+ min-height: 42px;
820
+ padding: var(--space-3) var(--space-4) var(--space-3) 38px;
821
+ border: 1px solid var(--border-subtle);
822
+ border-radius: var(--radius-control);
823
+ background: var(--surface-input);
824
+ color: var(--text-secondary);
825
+ font-size: 0.8125rem;
826
+ line-height: 1.45;
827
+ }
828
+
829
+ .status-bar::before {
830
+ position: absolute;
831
+ top: 50%;
832
+ left: var(--space-4);
833
+ width: 7px;
834
+ height: 7px;
835
+ border-radius: 50%;
836
+ background: var(--status-success);
837
+ box-shadow: 0 0 0 4px rgba(54, 179, 126, 0.1);
838
+ content: "";
839
+ transform: translateY(-50%);
840
+ }
841
+
842
+ .status-bar details {
843
+ margin-top: var(--space-2);
844
+ }
845
+
846
+ /* Tabs and feature workspace */
847
+ .learning-nav {
848
+ display: flex !important;
849
+ overflow: hidden;
850
+ margin-bottom: 0 !important;
851
+ border: 1px solid var(--border-subtle) !important;
852
+ border-bottom: 0 !important;
853
+ border-radius: var(--radius-panel) var(--radius-panel) 0 0 !important;
854
+ background: var(--surface-panel) !important;
855
+ }
856
+
857
+ .gradio-container fieldset.learning-nav {
858
+ overflow: hidden !important;
859
+ }
860
+
861
+ .learning-nav .wrap {
862
+ display: flex !important;
863
+ flex-wrap: nowrap !important;
864
+ width: 100%;
865
+ overflow-x: auto;
866
+ gap: var(--space-1) !important;
867
+ padding: var(--space-2) !important;
868
+ border: 0 !important;
869
+ background: transparent !important;
870
+ scrollbar-width: none;
871
+ }
872
+
873
+ .learning-nav .wrap::-webkit-scrollbar {
874
+ display: none;
875
+ }
876
+
877
+ .learning-nav label {
878
+ flex: 0 0 auto;
879
+ min-height: 44px !important;
880
+ margin: 0 !important;
881
+ padding: 0 var(--space-4) !important;
882
+ border: 0 !important;
883
+ border-radius: var(--radius-control) !important;
884
+ background: transparent !important;
885
+ box-shadow: none !important;
886
+ color: var(--text-tertiary) !important;
887
+ cursor: pointer;
888
+ white-space: nowrap;
889
+ }
890
+
891
+ .learning-nav label:hover {
892
+ background: var(--surface-hover) !important;
893
+ color: var(--text-secondary) !important;
894
+ }
895
+
896
+ .learning-nav label:has(input:checked) {
897
+ background: var(--accent-wash) !important;
898
+ color: var(--text-primary) !important;
899
+ }
900
+
901
+ .learning-nav label:has(input:focus-visible) {
902
+ outline: 2px solid var(--accent-hover) !important;
903
+ outline-offset: -2px !important;
904
+ }
905
+
906
+ .learning-nav input {
907
+ position: absolute !important;
908
+ width: 1px !important;
909
+ height: 1px !important;
910
+ opacity: 0 !important;
911
+ }
912
+
913
+ .learning-tabs {
914
+ overflow: hidden;
915
+ border: 1px solid var(--border-subtle) !important;
916
+ border-radius: 0 0 var(--radius-panel) var(--radius-panel) !important;
917
+ background: var(--surface-glass) !important;
918
+ box-shadow: inset 0 1px 0 var(--border-subtle) !important;
919
+ }
920
+
921
+ .learning-tabs > .tab-wrapper {
922
+ display: none !important;
923
+ }
924
+
925
+ .learning-tabs .tabitem {
926
+ padding: var(--space-6) !important;
927
+ background: transparent !important;
928
+ }
929
+
930
+ .feature-sub {
931
+ margin-bottom: var(--space-4) !important;
932
+ }
933
+
934
+ .feature-layout {
935
+ display: grid !important;
936
+ grid-template-columns: minmax(16rem, 0.7fr) minmax(0, 1.3fr) !important;
937
+ gap: var(--space-6) !important;
938
+ align-items: start !important;
939
+ }
940
+
941
+ .feature-controls,
942
+ .feature-output {
943
+ min-width: 0 !important;
944
+ padding: var(--space-5) !important;
945
+ border: 1px solid var(--border-subtle) !important;
946
+ border-radius: var(--radius-card) !important;
947
+ background: var(--surface-input) !important;
948
+ }
949
+
950
+ .result-markdown {
951
+ min-height: 260px;
952
+ }
953
+
954
+ .result-markdown h1,
955
+ .result-markdown h2,
956
+ .result-markdown h3 {
957
+ color: var(--text-primary) !important;
958
+ font-weight: 510 !important;
959
+ letter-spacing: -0.018em !important;
960
+ }
961
+
962
+ .result-markdown p,
963
+ .result-markdown li {
964
+ color: var(--text-secondary) !important;
965
+ line-height: 1.65 !important;
966
+ }
967
+
968
+ .qa-chat {
969
+ overflow: hidden;
970
+ border: 1px solid var(--border-subtle) !important;
971
+ border-radius: var(--radius-card) !important;
972
+ background:
973
+ radial-gradient(circle at 50% 0, var(--accent-wash), transparent 45%),
974
+ var(--surface-input) !important;
975
+ }
976
+
977
+ .qa-input {
978
+ margin-top: var(--space-3) !important;
979
+ }
980
+
981
+ /* Empty library */
982
+ .preview-col .gr-checkboxgroup {
983
+ min-height: 96px;
984
+ padding: var(--space-3) !important;
985
+ border: 1px dashed var(--border-default) !important;
986
+ border-radius: var(--radius-control) !important;
987
+ background: var(--surface-input) !important;
988
+ }
989
+
990
+ .preview-col .gr-dropdown {
991
+ padding: var(--space-2) !important;
992
+ border: 1px solid var(--border-subtle) !important;
993
+ border-radius: var(--radius-control) !important;
994
+ background: var(--surface-input) !important;
995
+ }
996
+
997
+ /* Footer */
998
+ .footer-text {
999
+ display: flex;
1000
+ align-items: center;
1001
+ gap: var(--space-4);
1002
+ padding: var(--space-8) 0 var(--space-4);
1003
+ border-top: 1px solid var(--border-subtle);
1004
+ color: var(--text-disabled);
1005
+ font-size: 0.75rem;
1006
+ }
1007
+
1008
+ .footer-text span {
1009
+ color: var(--text-tertiary);
1010
+ font-weight: 510;
1011
+ }
1012
+
1013
+ .gradio-container footer {
1014
+ color: var(--text-disabled) !important;
1015
+ opacity: 0.66;
1016
+ }
1017
+
1018
+ /* Responsive */
1019
+ @media (max-width: 1024px) {
1020
+ .hero-shell {
1021
+ grid-template-columns: minmax(0, 1fr) minmax(13rem, 0.55fr);
1022
+ min-height: 360px;
1023
+ }
1024
+
1025
+ .main-layout {
1026
+ grid-template-columns: minmax(16rem, 20rem) minmax(0, 1fr) !important;
1027
+ }
1028
+
1029
+ .workflow-strip {
1030
+ grid-template-columns: 1fr;
1031
+ }
1032
+ }
1033
+
1034
+ @media (max-width: 768px) {
1035
+ .gradio-container {
1036
+ padding-inline: var(--space-4) !important;
1037
+ }
1038
+
1039
+ .product-header {
1040
+ min-height: 60px;
1041
+ }
1042
+
1043
+ .header-status {
1044
+ display: none;
1045
+ }
1046
+
1047
+ .hero-shell {
1048
+ grid-template-columns: 1fr;
1049
+ min-height: auto;
1050
+ padding: var(--space-12) 0 var(--space-10);
1051
+ }
1052
+
1053
+ .hero-copy h1 {
1054
+ font-size: clamp(2.35rem, 11vw, 3.6rem);
1055
+ }
1056
+
1057
+ .hero-visual {
1058
+ min-height: 230px;
1059
+ }
1060
+
1061
+ .document-stack {
1062
+ transform: scale(0.82) rotate(4deg);
1063
+ }
1064
+
1065
+ .workflow-steps {
1066
+ grid-template-columns: repeat(2, minmax(0, 1fr));
1067
+ row-gap: var(--space-3);
1068
+ }
1069
+
1070
+ .main-layout,
1071
+ .feature-layout {
1072
+ grid-template-columns: minmax(0, 1fr) !important;
1073
+ }
1074
+
1075
+ .control-stack,
1076
+ .preview-col,
1077
+ .learning-tabs .tabitem {
1078
+ padding: var(--space-5) !important;
1079
+ }
1080
+
1081
+ .qa-chat {
1082
+ height: 420px !important;
1083
+ }
1084
+ }
1085
+
1086
+ @media (max-width: 480px) {
1087
+ .gradio-container {
1088
+ padding-inline: var(--space-3) !important;
1089
+ }
1090
+
1091
+ .hero-shell {
1092
+ padding-top: var(--space-10);
1093
+ }
1094
+
1095
+ .hero-copy h1 br {
1096
+ display: none;
1097
+ }
1098
+
1099
+ .hero-copy p {
1100
+ font-size: 1rem;
1101
+ }
1102
+
1103
+ .hero-visual {
1104
+ min-height: 205px;
1105
+ }
1106
+
1107
+ .workflow-strip,
1108
+ .control-stack,
1109
+ .preview-col,
1110
+ .learning-tabs .tabitem {
1111
+ padding: var(--space-4) !important;
1112
+ }
1113
+
1114
+ .workflow-steps {
1115
+ grid-template-columns: minmax(0, 1fr);
1116
+ }
1117
+
1118
+ .workflow-steps li {
1119
+ white-space: normal;
1120
+ }
1121
+
1122
+ .learning-nav .wrap {
1123
+ gap: 2px !important;
1124
+ }
1125
+
1126
+ .learning-nav label {
1127
+ padding-inline: 3px !important;
1128
+ font-size: 0.6875rem !important;
1129
+ }
1130
+
1131
+ .panel-heading {
1132
+ align-items: center;
1133
+ }
1134
+
1135
+ }
1136
+
1137
+ @media (prefers-reduced-motion: reduce) {
1138
+ html {
1139
+ scroll-behavior: auto;
1140
+ }
1141
+
1142
+ *,
1143
+ *::before,
1144
+ *::after {
1145
+ scroll-behavior: auto !important;
1146
+ transition-duration: 0.01ms !important;
1147
+ }
1148
+ }
test.ipynb DELETED
File without changes
tests/test_api.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI boundary tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi.testclient import TestClient
6
+
7
+ from src.config import settings
8
+ from src.interfaces.api import app
9
+
10
+
11
+ def test_health_returns_status() -> None:
12
+ """Given a running API, health should be available without external services."""
13
+ response = TestClient(app).get("/health")
14
+
15
+ assert response.status_code == 200
16
+ assert response.json() == {"status": "ok"}
17
+
18
+
19
+ def test_upload_rejects_non_pdf_content() -> None:
20
+ """Given a fake PDF, upload should reject it before writing or embedding."""
21
+ response = TestClient(app).post(
22
+ "/upload",
23
+ files={"file": ("notes.pdf", b"not a pdf", "application/pdf")},
24
+ )
25
+
26
+ assert response.status_code == 400
27
+
28
+
29
+ def test_configured_api_key_protects_documents(monkeypatch) -> None:
30
+ """Configured API auth should reject missing or incorrect keys."""
31
+ monkeypatch.setattr(settings, "api_key", "test-secret")
32
+ monkeypatch.setattr("src.interfaces.api.list_documents", lambda: [])
33
+ client = TestClient(app)
34
+
35
+ assert client.get("/documents").status_code == 401
36
+ assert client.get("/documents", headers={"X-API-Key": "wrong"}).status_code == 401
37
+ assert client.get("/documents", headers={"X-API-Key": "test-secret"}).status_code == 200
tests/test_boundaries.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Input and rendering boundary tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from pydantic import ValidationError
7
+
8
+ from src.export import export
9
+ from src.filters import MetadataFilter
10
+ from src.learning import _validate_items
11
+ from src.schemas import (
12
+ Citation,
13
+ Flashcard,
14
+ FlashcardSet,
15
+ QuizItem,
16
+ QuizSet,
17
+ RagAnswer,
18
+ Summary,
19
+ )
20
+
21
+
22
+ def test_metadata_filter_rejects_negative_pages() -> None:
23
+ """Given an impossible page number, parsing should fail at the boundary."""
24
+ with pytest.raises(ValidationError):
25
+ MetadataFilter.model_validate({"page": -1})
26
+
27
+
28
+ def test_metadata_filter_rejects_unknown_fields() -> None:
29
+ """Given a mistyped filter, parsing should fail instead of silently ignoring it."""
30
+ with pytest.raises(ValidationError):
31
+ MetadataFilter.model_validate({"filenmae": "doc.pdf"})
32
+
33
+
34
+ def test_markdown_export_escapes_untrusted_html() -> None:
35
+ """Given model and filename HTML, exported Markdown must not contain executable tags."""
36
+ result = RagAnswer(
37
+ question="q",
38
+ answer='<img src=x onerror="alert(1)">',
39
+ citations=[
40
+ Citation(
41
+ source_index=1,
42
+ source_marker="S1",
43
+ filename="<script>alert(2)</script>.pdf",
44
+ page=1,
45
+ )
46
+ ],
47
+ )
48
+
49
+ rendered = export(result, fmt="md")
50
+
51
+ assert "<img" not in rendered
52
+ assert "<script>" not in rendered
53
+ assert "&lt;img" in rendered
54
+ assert "&lt;script&gt;" in rendered
55
+
56
+
57
+ @pytest.mark.parametrize(
58
+ "result",
59
+ [
60
+ RagAnswer(
61
+ question="q",
62
+ answer="[click](javascript:alert(1)) ![pixel](https://tracker.invalid/pixel)",
63
+ ),
64
+ Summary(
65
+ scope="corpus",
66
+ summary="[click](javascript:alert(1)) ![pixel](https://tracker.invalid/pixel)",
67
+ ),
68
+ QuizSet(
69
+ scope="corpus",
70
+ items=[
71
+ QuizItem(
72
+ question="[click](javascript:alert(1))",
73
+ options=["![pixel](https://tracker.invalid/pixel)", "B", "C", "D"],
74
+ correct_index=0,
75
+ explanation="https://tracker.invalid/explanation",
76
+ )
77
+ ],
78
+ ),
79
+ FlashcardSet(
80
+ scope="corpus",
81
+ cards=[
82
+ Flashcard(
83
+ front="[click](javascript:alert(1))",
84
+ back="![pixel](https://tracker.invalid/pixel)",
85
+ hint="https://tracker.invalid/hint",
86
+ )
87
+ ],
88
+ ),
89
+ ],
90
+ )
91
+ def test_markdown_export_neutralizes_external_links_and_images(result) -> None:
92
+ rendered = export(result, fmt="md")
93
+
94
+ assert "](javascript:" not in rendered
95
+ assert "![" not in rendered
96
+ assert "https://tracker.invalid" not in rendered
97
+
98
+
99
+ def test_markdown_export_keeps_hostile_filename_inside_citation() -> None:
100
+ result = RagAnswer(
101
+ question="q",
102
+ answer="answer",
103
+ citations=[
104
+ Citation(
105
+ source_index=1,
106
+ source_marker="S1",
107
+ filename="notes`\n# injected [link](https://tracker.invalid).pdf",
108
+ page=1,
109
+ )
110
+ ],
111
+ )
112
+
113
+ rendered = export(result, fmt="md")
114
+
115
+ assert "\n# injected" not in rendered
116
+ assert "](https://tracker.invalid)" not in rendered
117
+
118
+
119
+ def test_quiz_item_without_valid_source_marker_is_rejected() -> None:
120
+ """Given fabricated citation markers, a supposedly grounded item must be rejected."""
121
+ payload = {
122
+ "items": [
123
+ {
124
+ "question": "Question",
125
+ "options": ["A", "B", "C", "D"],
126
+ "correct_index": 0,
127
+ "explanation": "Explanation",
128
+ "source_markers": ["S999"],
129
+ }
130
+ ]
131
+ }
132
+
133
+ with pytest.raises(RuntimeError, match="No valid quiz items"):
134
+ _validate_items(payload, "items", QuizItem, "question", "quiz items", {"S1"})
tests/test_config.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration normalization tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from src.config import Settings
6
+
7
+
8
+ def test_blank_api_key_disables_api_auth(monkeypatch) -> None:
9
+ """A blank documented API key should behave like missing configuration."""
10
+ monkeypatch.setenv("RAG_API_KEY", " ")
11
+
12
+ configured = Settings(_env_file=None)
13
+
14
+ assert configured.api_key is None
tests/test_entrypoints.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """User-facing entrypoint regression tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+ import sys
7
+
8
+
9
+ def test_cli_help_runs_from_project_root() -> None:
10
+ """Given the installed project, CLI help should run without import workarounds."""
11
+ result = subprocess.run(
12
+ [sys.executable, "-m", "src.interfaces.cli", "--help"],
13
+ check=False,
14
+ capture_output=True,
15
+ text=True,
16
+ )
17
+
18
+ assert result.returncode == 0, result.stderr
19
+ assert "debug-retrieval" in result.stdout
20
+
21
+
22
+ def test_api_exposes_complete_learning_surface() -> None:
23
+ """Given the API module, all advertised learning routes should be registered."""
24
+ from src.interfaces.api import app
25
+
26
+ routes = {route.path for route in app.routes}
27
+
28
+ assert {
29
+ "/health",
30
+ "/documents",
31
+ "/upload",
32
+ "/ask",
33
+ "/summarize",
34
+ "/quiz",
35
+ "/flashcards",
36
+ } <= routes
37
+
38
+
39
+ def test_gradio_app_imports_without_optional_logo() -> None:
40
+ """Given no logo asset, importing the Gradio application should still succeed."""
41
+ from app import demo
42
+
43
+ assert demo is not None