File size: 2,831 Bytes
b1f23a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8531b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1f23a6
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional

from app.services.page_service import PageService
from app.database.sqlite_db import get_db, SQLiteDB

router = APIRouter(prefix="/reference", tags=["Reference"])

class ReferenceLookupRequest(BaseModel):
    vol: int
    page: int
    type: str # 'footnote' | 'abbrev'
    id: str
    context: Optional[str] = None

def get_page_service(db: SQLiteDB = Depends(get_db)) -> PageService:
    return PageService(db)

@router.get("/lookup")
async def lookup_reference(
    vol: int,
    page: int,
    type: str,
    id: str,
    service: PageService = Depends(get_page_service),
):
    if type == "footnote":
        content = service.get_footnote(vol, page, id)
        if not content:
            return {"content": "ไม่พบข้อมูลเชิงอรรถนี้บนหน้าเว็บปัจจุบัน", "found": False}
        return {"content": content, "found": True}
    
    elif type == "abbrev":
        # Query DB directly — no LLM or RAG service needed (all abbrevs pre-indexed)
        import json, re
        clean_id = re.sub(r'[()\[\]-]', '', id).strip()
        lookup_id = "_default"
        if clean_id and re.match(r'^[\u0E50-\u0E59\d]+$', clean_id):
            lookup_id = clean_id
        
        with service.db.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""
                SELECT content FROM reference_markers
                WHERE volume_num = ? AND page_num = ? AND marker_id = ? AND type = 'abbrev'
            """, (vol, page, lookup_id))
            row = cursor.fetchone()
        
        if row:
            content = row["content"]
            if content.startswith('['):
                try:
                    entries = json.loads(content)
                    if isinstance(entries, list):
                        if entries and isinstance(entries[0], str):
                            return {"content": "\n\n".join(entries), "found": True}
                        parts = [e.get("expansion", "") for e in entries if isinstance(e, dict) and e.get("expansion", "")]
                        if parts:
                            return {"content": "\n\n".join(parts), "found": True}
                except (json.JSONDecodeError, TypeError, AttributeError):
                    pass
                return {"content": content, "found": True}
            return {"content": content, "found": True}
        
        return {"content": f"(ย่อ) — ยังไม่มีข้อมูลขยายความในฐานข้อมูลเล่ม {vol} หน้า {page}", "found": False}
    
    else:
        raise HTTPException(status_code=400, detail="Invalid reference type")