dhammawatthumpra commited on
Commit
c78c964
·
1 Parent(s): 98474d5

expand auto-correct: PyThaiNLP + confusion map for all 293 POPULAR_TERMS

Browse files
tipatika-wiki/wiki/concepts/search-pipeline.md CHANGED
@@ -30,10 +30,27 @@ ChromaDB + Sentence Transformers (Qwen3-Embedding-0.6B)
30
  ### 4. Autocomplete Suggestions
31
  ดูที่ [[search-autocomplete]]
32
 
33
- ## Auto-correction
34
 
35
- `PALI_CORRECTIONS` dict ใน `search_service.py` แปลงคำสะกดผิดทั่วไปก่อน query
36
- เช่น "นิพาน" → "นิพพาน", "อริยะสัจ" → "อริยสัจ", "มรนสติ" → "มรณสติ"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  ## Zero-Result Logging
39
 
 
30
  ### 4. Autocomplete Suggestions
31
  ดูที่ [[search-autocomplete]]
32
 
33
+ ## Auto-correction (2-stage)
34
 
35
+ ระบบ auto-correct มี 2 ขั้นตอนที่ทำงานต่อกัน:
36
+
37
+ ### Stage A: Pali Auto-generated (PALI_CORRECTIONS_FULL)
38
+
39
+ `PALI_CORRECTIONS` + auto-generated variants จาก confusion map **ครอบคลุม POPULAR_TERMS ทั้ง 293 คำ**
40
+
41
+ - `THAI_PALI_CONFUSIONS` map character ที่คนไทยมักพิมพ์ผิดสลับกัน (ส↔ศ↔ษ, ฏ↔ต↔ฐ↔ถ, ณ↔น, ภ↔พ, ฬ↔ล)
42
+ - `_generate_pali_variants()` สร้าง misspellings ที่เป็นไปได้โดยเปลี่ยนทีละ character
43
+ - `_build_pali_corrections()` เรียกครั้งเดียวตอน module load รวมคำที่ hand-curated (~55 คำ) + auto-generated (~200+ คำ)
44
+ - เช่น "นิพาน" → "นิพพาน", "มรนสติ" → "มรณสติ", "สังสารวัศ" → "สังสารวัฏ" (auto-generated)
45
+
46
+ ### Stage B: PyThaiNLP (general Thai)
47
+
48
+ ถ้า Stage A ไม่ match ให้ลอง `pythainlp.spell.correct()` สำหรับการสะกดผิดทั่วไปของภาษาไทย
49
+ เช่น "ทุกขะ" → "ทุกข์", "โพธิ์" → "โพธิ"
50
+
51
+ - Optional dependency: `pip install pythainlp` (ถ้าไม่มีก็ข้ามไปโดยไม่ error)
52
+ - Import แบบ try/except — ไม่ทำให้ server crash ถ้าไม่ได้ติดตั้ง
53
+ - Tokenize ด้วย `word_tokenize()` แล้วแก้ทีละ token
54
 
55
  ## Zero-Result Logging
56
 
tipatika-wiki/wiki/log.md CHANGED
@@ -38,3 +38,19 @@ Summary:
38
 
39
  Files changed in codebase:
40
  - `search_service.py` — PALI_CORRECTIONS: added "มรนสติ" → "มรณสติ"; log_search guarded by `if total_count > 0`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  Files changed in codebase:
40
  - `search_service.py` — PALI_CORRECTIONS: added "มรนสติ" → "มรณสติ"; log_search guarded by `if total_count > 0`
41
+
42
+ ## 2026-04-30 (expand | 2-stage Auto-correct: PyThaiNLP + Confusion Map)
43
+
44
+ Pages updated: [[search-pipeline]]
45
+
46
+ Summary:
47
+ - Added `THAI_PALI_CONFUSIONS` character confusion map (ส↔ศ↔ษ, ฏ↔ต↔ฐ↔ถ, ณ↔น, ภ↔พ, ฬ↔ล)
48
+ - Added `_generate_pali_variants()` that generates misspellings for any Pali term
49
+ - Added `_build_pali_corrections()` — auto-generates corrections for all 293 POPULAR_TERMS at load time
50
+ - Renamed `PALI_CORRECTIONS` → `PALI_CORRECTIONS_FULL` (hand-curated ~55 + auto-generated ~200+)
51
+ - Added `_pythai_autocorrect()` — optional PyThaiNLP integration for general Thai typos
52
+ - search() now runs 2-stage: Pali-specific dict → PyThaiNLP fallback
53
+
54
+ Files changed in codebase:
55
+ - `search_service.py` — THAI_PALI_CONFUSIONS, _generate_pali_variants(), _pythai_autocorrect(), PALI_CORRECTIONS_FULL, 2-stage search
56
+ - `requirements.txt` — added pythainlp>=5.0
webapp/tipitaka-api/app/services/search_service.py CHANGED
@@ -4,8 +4,89 @@ from typing import List
4
  from app.database.sqlite_db import SQLiteDB
5
  from app.schemas import SearchResponse, SearchResultItem
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  # ── Pali/Dhamma Auto-correction (full list from v2.1) ─────────────
8
- PALI_CORRECTIONS = {
9
  # อริยสัจ
10
  "อริยะสัจ": "อริยสัจ", "อริยะสัจ4": "อริยสัจ", "อริยสัจ4": "อริยสัจ ๔",
11
  "สี่อริยสัจ": "อริยสัจ", "4อริยสัจ": "อริยสัจ",
@@ -54,6 +135,7 @@ PALI_CORRECTIONS = {
54
  "มหาบุรษ": "มหาบุรุษ",
55
  }
56
 
 
57
  def to_thai_digits(s: str) -> str:
58
  return s.translate(str.maketrans("0123456789", "๐๑๒๓๔๕๖๗๘๙"))
59
 
@@ -142,6 +224,27 @@ POPULAR_TERMS: List[str] = [
142
  ]
143
 
144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  class SearchService:
146
  def __init__(self, db: SQLiteDB):
147
  self.db = db
@@ -270,9 +373,16 @@ class SearchService:
270
  def search(self, query: str, limit: int = 50, offset: int = 0) -> SearchResponse:
271
  start_time = time.time()
272
 
273
- # 1. Auto-correct & normalise
274
  q = query.strip()
275
- corrected_q = PALI_CORRECTIONS.get(q, q)
 
 
 
 
 
 
 
276
  thai_q = to_thai_digits(corrected_q)
277
  like_pattern = f"%{thai_q}%"
278
 
 
4
  from app.database.sqlite_db import SQLiteDB
5
  from app.schemas import SearchResponse, SearchResultItem
6
 
7
+ # ── Optional: PyThaiNLP for general Thai spell-checking ───────────
8
+ try:
9
+ from pythainlp.spell import correct as pythai_spell_correct
10
+ from pythainlp.tokenize import word_tokenize as pythai_tokenize
11
+ HAS_PYTHAINLP = True
12
+ except ImportError:
13
+ HAS_PYTHAINLP = False
14
+
15
+ # ── Thai Pali Character Confusion Map ─────────────────────────────
16
+ # These are character-level substitution errors commonly made when
17
+ # typing Pali terms in Thai script (คนไทยมักพิมพ์ส/ศ/ษ สลับกัน ฯลฯ)
18
+ THAI_PALI_CONFUSIONS = {
19
+ # ส group — all map to /s/ sound
20
+ "ส": ["ศ", "ษ"],
21
+ "ศ": ["ส", "ษ"],
22
+ "ษ": ["ส", "ศ"],
23
+ # ฏ group — retroflex / dental stops
24
+ "ฏ": ["ต", "ฐ"],
25
+ "ฐ": ["ต", "ฏ", "ถ"],
26
+ "ถ": ["ต", "ฐ", "ฑ"],
27
+ "ฑ": ["ต", "ฐ", "ถ", "ฒ"],
28
+ "ฒ": ["ด", "ฑ", "ท"],
29
+ # ณ / น
30
+ "ณ": ["น"],
31
+ "น": ["ณ"],
32
+ # ภ / พ
33
+ "ภ": ["พ"],
34
+ "พ": ["ภ"],
35
+ # ฬ / ล
36
+ "ฬ": ["ล"],
37
+ "ล": ["ฬ"],
38
+ }
39
+
40
+
41
+ def _generate_pali_variants(word: str) -> set[str]:
42
+ """Generate common misspellings for a Pali term via single-character substitutions.
43
+
44
+ For each character in `word`, if it belongs to a confusion group, replace it
45
+ with each alternative to produce a likely misspelling. Only single-character
46
+ changes are generated (not combinatorial) to keep the map lean.
47
+ """
48
+ variants: set[str] = set()
49
+ for i, ch in enumerate(word):
50
+ if ch in THAI_PALI_CONFUSIONS:
51
+ for alt in THAI_PALI_CONFUSIONS[ch]:
52
+ variant = word[:i] + alt + word[i + 1:]
53
+ if variant != word:
54
+ variants.add(variant)
55
+ return variants
56
+
57
+
58
+ def _pythai_autocorrect(q: str) -> str:
59
+ """Use PyThaiNLP to correct general Thai spelling errors (not Pali-specific).
60
+
61
+ Falls back to the original query if PyThaiNLP is unavailable or raises.
62
+ Only applies corrections when at least one token changes.
63
+ """
64
+ if not HAS_PYTHAINLP or not q:
65
+ return q
66
+ try:
67
+ # Tokenize then spell-correct each token independently
68
+ tokens = pythai_tokenize(q)
69
+ corrected_tokens = []
70
+ changed = False
71
+ for tok in tokens:
72
+ if len(tok) <= 1: # Skip single-char tokens (spaces, punctuation)
73
+ corrected_tokens.append(tok)
74
+ continue
75
+ suggestions = pythai_spell_correct(tok)
76
+ if suggestions and suggestions[0] != tok:
77
+ corrected_tokens.append(suggestions[0])
78
+ changed = True
79
+ else:
80
+ corrected_tokens.append(tok)
81
+ if changed:
82
+ return "".join(corrected_tokens)
83
+ except Exception:
84
+ pass
85
+ return q
86
+
87
+
88
  # ── Pali/Dhamma Auto-correction (full list from v2.1) ─────────────
89
+ PALI_CORRECTIONS: dict[str, str] = {
90
  # อริยสัจ
91
  "อริยะสัจ": "อริยสัจ", "อริยะสัจ4": "อริยสัจ", "อริยสัจ4": "อริยสัจ ๔",
92
  "สี่อริยสัจ": "อริยสัจ", "4อริยสัจ": "อริยสัจ",
 
135
  "มหาบุรษ": "มหาบุรุษ",
136
  }
137
 
138
+
139
  def to_thai_digits(s: str) -> str:
140
  return s.translate(str.maketrans("0123456789", "๐๑๒๓๔๕๖๗๘๙"))
141
 
 
224
  ]
225
 
226
 
227
+ def _build_pali_corrections() -> dict[str, str]:
228
+ """Extend PALI_CORRECTIONS with auto-generated variants from all POPULAR_TERMS.
229
+
230
+ For every term in POPULAR_TERMS, this generates likely misspellings
231
+ using character confusion groups (ส↔ศ↔ษ, ฏ↔ต↔ฐ, ณ↔น, ภ↔พ, ฬ↔ล, etc.)
232
+ and adds them to the corrections dict.
233
+
234
+ This is called once at module load time so there is zero runtime cost.
235
+ """
236
+ corrections = dict(PALI_CORRECTIONS)
237
+ for term in POPULAR_TERMS:
238
+ for variant in _generate_pali_variants(term):
239
+ if variant not in corrections:
240
+ corrections[variant] = term
241
+ return corrections
242
+
243
+
244
+ # Build the full corrections dict at load time (hand-curated + auto-generated)
245
+ PALI_CORRECTIONS_FULL = _build_pali_corrections()
246
+
247
+
248
  class SearchService:
249
  def __init__(self, db: SQLiteDB):
250
  self.db = db
 
373
  def search(self, query: str, limit: int = 50, offset: int = 0) -> SearchResponse:
374
  start_time = time.time()
375
 
376
+ # ── 1. Auto-correct pipeline ─────────────────────────────
377
  q = query.strip()
378
+
379
+ # Stage A: Pali-specific correction (explicit dict lookup + auto-generated variants)
380
+ corrected_q = PALI_CORRECTIONS_FULL.get(q, q)
381
+
382
+ # Stage B: General Thai spelling correction via PyThaiNLP
383
+ if corrected_q == q:
384
+ corrected_q = _pythai_autocorrect(q)
385
+
386
  thai_q = to_thai_digits(corrected_q)
387
  like_pattern = f"%{thai_q}%"
388
 
webapp/tipitaka-api/requirements.txt CHANGED
@@ -8,3 +8,4 @@ chromadb>=1.5
8
  sentence-transformers>=3.0
9
  huggingface_hub>=0.20
10
  torch>=2.0
 
 
8
  sentence-transformers>=3.0
9
  huggingface_hub>=0.20
10
  torch>=2.0
11
+ pythainlp>=5.0