File size: 6,468 Bytes
5a412ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
from fastapi import APIRouter, HTTPException, status
from fastapi.responses import JSONResponse
from src.utils.logger import logger
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
import json
import os

router = APIRouter(prefix="/pronunciation", tags=["Pronunciation"])


class Level(BaseModel):
    id: str
    name: str
    description: str
    color: str


class Vocabulary(BaseModel):
    word: str
    ipa: str
    vietnamese: str
    audioUrl: str


class Sentence(BaseModel):
    text: str
    ipa: str
    vietnamese: str
    audioUrl: str


class PronunciationLesson(BaseModel):
    id: str
    title: str
    description: str
    level: str
    vocabulary: List[Vocabulary]
    sentence: Sentence


class LevelsResponse(BaseModel):
    levels: List[Level]
    total: int


class LessonsResponse(BaseModel):
    lessons: List[PronunciationLesson]
    total: int
    level: str


class LessonDetailResponse(BaseModel):
    lesson: PronunciationLesson


def load_pronunciation_data() -> Dict[str, Any]:
    """Load pronunciation lessons data from JSON file"""
    try:
        data_file_path = os.path.join(
            os.path.dirname(__file__), "..", "..", "data", "pronunciation_lessons.json"
        )

        if not os.path.exists(data_file_path):
            logger.warning(f"Pronunciation lessons file not found at {data_file_path}")
            return {"levels": [], "lessons": {}}

        with open(data_file_path, "r", encoding="utf-8") as file:
            data = json.load(file)

        return data
    except Exception as e:
        logger.error(f"Error loading pronunciation lessons data: {str(e)}")
        return {"levels": [], "lessons": {}}


@router.get("/levels", response_model=LevelsResponse)
async def get_levels():
    """
    Get all available levels for pronunciation practice
    
    Returns:
        LevelsResponse: Contains list of all levels and total count
    """
    try:
        data = load_pronunciation_data()
        levels_data = data.get("levels", [])
        
        levels = [Level(**level_data) for level_data in levels_data]
        
        return LevelsResponse(levels=levels, total=len(levels))
    except Exception as e:
        logger.error(f"Error retrieving levels: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve levels",
        )


@router.get("/lessons/{level_id}", response_model=LessonsResponse)
async def get_lessons_by_level(level_id: str):
    """
    Get all lessons for a specific level
    
    Args:
        level_id (str): The level ID (beginner, elementary, etc.)
        
    Returns:
        LessonsResponse: Contains list of lessons for the specified level
    """
    try:
        data = load_pronunciation_data()
        lessons_data = data.get("lessons", {})
        
        if level_id not in lessons_data:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Level '{level_id}' not found",
            )
        
        level_lessons = lessons_data[level_id]
        lessons = [PronunciationLesson(**lesson_data) for lesson_data in level_lessons]
        
        return LessonsResponse(lessons=lessons, total=len(lessons), level=level_id)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error retrieving lessons for level {level_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve lessons",
        )


@router.get("/lesson/{lesson_id}", response_model=LessonDetailResponse)
async def get_lesson_detail(lesson_id: str):
    """
    Get detailed information about a specific lesson
    
    Args:
        lesson_id (str): The unique identifier of the lesson
        
    Returns:
        LessonDetailResponse: Contains the lesson details
    """
    try:
        data = load_pronunciation_data()
        lessons_data = data.get("lessons", {})
        
        # Search for the lesson across all levels
        found_lesson = None
        for level_id, level_lessons in lessons_data.items():
            for lesson_data in level_lessons:
                if lesson_data.get("id") == lesson_id:
                    found_lesson = lesson_data
                    break
            if found_lesson:
                break
        
        if not found_lesson:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Lesson with ID '{lesson_id}' not found",
            )
        
        lesson = PronunciationLesson(**found_lesson)
        
        return LessonDetailResponse(lesson=lesson)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error retrieving lesson {lesson_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve lesson",
        )


@router.get("/search/level/{level_id}/title/{title}")
async def search_lessons_by_title(level_id: str, title: str):
    """
    Search lessons by title within a specific level
    
    Args:
        level_id (str): The level ID to search within
        title (str): Part of the lesson title to search for
        
    Returns:
        LessonsResponse: Contains list of matching lessons
    """
    try:
        data = load_pronunciation_data()
        lessons_data = data.get("lessons", {})
        
        if level_id not in lessons_data:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Level '{level_id}' not found",
            )
        
        level_lessons = lessons_data[level_id]
        matching_lessons = [
            lesson_data for lesson_data in level_lessons
            if title.lower() in lesson_data.get("title", "").lower()
        ]
        
        lessons = [PronunciationLesson(**lesson_data) for lesson_data in matching_lessons]
        
        return LessonsResponse(lessons=lessons, total=len(lessons), level=level_id)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error searching lessons by title '{title}' in level {level_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to search lessons",
        )