Spaces:
Running
feat(SCRUM-34): 7-component pronunciation assessment
Browse files- Add POST /grade/pronunciation/practice endpoint
- Implement DTW phoneme alignment with IPA feature distance
(place/manner/voicing weighted: 0.5/0.35/0.15)
- Add pronunciation_analysis/ package with 7 components:
1. individual_sounds: Wav2Vec2 + DTW alignment
2. word_stress: Parselmouth F0 per-syllable + librosa onset detection
3. sentence_stress: F0 peak mapping + isochrony rhythm check
4. linking: Rule-based C+V / gemination / intrusive / elision
5. intonation: F0 contour rising/falling/flat detection
6. chunking: Pause detection + speech rate WPM analysis
7. contracted_words: 64-entry contraction dictionary
- Add weighted scoring by target_type:
word (60/35/5%), phrase (35/20/25/10/10%), sentence (30/20/15/15/10/5/5%)
- Add rate limiting: 30 req/min per IP sliding window
- Add praat-parselmouth + dtw-python dependencies
- Add 20 unit tests (all passing, mocked AI models)
Closes SCRUM-34
Files changed (13)
- requirements.txt+3-1
- scripts/test_pronunciation.pyAdded+244
- src/api.py+207-3
- src/pronunciation.py+554-2
- src/pronunciation_analysis/__init__.pyAdded+27
- src/pronunciation_analysis/chunking.pyAdded+209
- src/pronunciation_analysis/contracted_words.pyAdded+203
- src/pronunciation_analysis/individual_sounds.pyAdded+53
- src/pronunciation_analysis/intonation.pyAdded+157
- src/pronunciation_analysis/linking.pyAdded+230
- src/pronunciation_analysis/scorer.pyAdded+219
- src/pronunciation_analysis/sentence_stress.pyAdded+187
- src/pronunciation_analysis/word_stress.pyAdded+364
17 unmodified lines1819202117 unmodified lineslibrosaopenai-whispernumpypython-multipart17 unmodified lines18192021222317 unmodified lineslibrosaopenai-whispernumpypython-multipartdtw-python>=1.3.0praat-parselmouth>=0.4.3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""Unit Tests for SCRUM-34: DTW Phoneme Alignment EngineChạy: python -m pytest scripts/test_pronunciation.py -v
NOTE: Test file import trực tiếp các hàm pure (DTW/scoring/feedback)bằng cách mock torch/transformers trước khi import module, tránh loadWav2Vec2 model (~1GB) mỗi lần chạy test."""import sysimport osfrom unittest.mock import MagicMock
# --- Mock heavy AI dependencies trước khi import pronunciation module ---# Điều này cho phép test các hàm pure (tokenize_ipa, align_phonemes_dtw,# compute_practice_score, generate_rule_feedback) mà không cần GPU/model._MOCKED_MODULES = [ "torch", "transformers", "transformers.Wav2Vec2ForCTC", "transformers.AutoTokenizer", "transformers.Wav2Vec2FeatureExtractor", "librosa",]for mod_name in _MOCKED_MODULES: if mod_name not in sys.modules: sys.modules[mod_name] = MagicMock()
# Cũng mock subprocess để tránh gọi espeak-ng thật trong testsimport subprocess as _subprocess_real_orig_run = _subprocess_real.rundef _mock_espeak(cmd, **kwargs): """Trả về IPA giả khi test gọi eSpeak.""" mock = MagicMock() mock.returncode = 1 # Giả lập không tìm thấy eSpeak → "N/A" return mock
_subprocess_real.run = _mock_espeak
# Đảm bảo import được từ src/ khi chạy từ rootsys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from src.pronunciation import ( tokenize_ipa, align_phonemes_dtw, compute_practice_score, generate_rule_feedback, _ipa_feature_distance,)
# Khôi phục subprocess.run sau khi import xong_subprocess_real.run = _orig_run
# ============================================================# TEST: tokenize_ipa# ============================================================
def test_tokenize_ipa_basic(): """Tách phoneme đơn giản.""" result = tokenize_ipa("kæt") assert result == ["k", "æ", "t"], f"Expected ['k','æ','t'], got {result}"
def test_tokenize_ipa_with_stress(): """Giữ stress marks trong tokens.""" result = tokenize_ipa("ˈstʌdənt") assert "ˈ" in result assert "s" in result assert "t" in result
def test_tokenize_ipa_diphthongs(): """Diphthong phải là 1 token, không bị split.""" result = tokenize_ipa("eɪm") # 'aim' assert "eɪ" in result, f"Expected diphthong 'eɪ' as one token, got {result}" assert "ɪ" not in result or result.index("eɪ") >= 0
def test_tokenize_ipa_affricates(): """Affricate tʃ phải là 1 token.""" result = tokenize_ipa("tʃɪn") # 'chin' assert "tʃ" in result, f"Expected affricate 'tʃ' as one token, got {result}"
def test_tokenize_ipa_empty(): """Chuỗi rỗng → list rỗng.""" assert tokenize_ipa("") == [] assert tokenize_ipa("N/A") == [] assert tokenize_ipa("Error") == []
# ============================================================# TEST: IPA feature distance# ============================================================
def test_feature_distance_identical(): """Cùng phoneme → distance = 0.""" assert _ipa_feature_distance("p", "p") == 0.0 assert _ipa_feature_distance("t", "t") == 0.0
def test_feature_distance_voicing_pair(): """p/b chỉ khác voicing → distance nhỏ.""" d_pb = _ipa_feature_distance("p", "b") d_pt = _ipa_feature_distance("p", "t") assert d_pb < d_pt, "p/b (voicing only) phải gần nhau hơn p/t (place khác)"
def test_feature_distance_consonant_vowel(): """Consonant vs vowel → distance gần 1.""" d = _ipa_feature_distance("p", "æ") assert d >= 0.8, f"Consonant vs vowel phải có distance ≥ 0.8, got {d}"
# ============================================================# TEST: align_phonemes_dtw# ============================================================
def test_align_perfect_match(): """Hai chuỗi IPA giống nhau → tất cả is_correct=True.""" results = align_phonemes_dtw("kæt", "kæt") for r in results: assert r["is_correct"] == True, f"Perfect match phải all correct: {r}" assert all(r["error_type"] == "correct" for r in results)
def test_align_deletion_final_t(): """'studen' (không có /t/ cuối) → phải có deletion error.""" # expected: 'student' → /ˈstjuːdənt/ # actual: 'studen' → /ˈstjuːdən/ (thiếu /t/ cuối) results = align_phonemes_dtw("ˈstjuːdən", "ˈstjuːdənt") error_types = [r["error_type"] for r in results] assert "deletion" in error_types, ( f"'studen' vs 'student' phải có deletion error, got error_types={error_types}" )
def test_align_substitution_th_to_d(): """Substitution: /ð/ → /d/ (lỗi phổ biến của người học VN).""" results = align_phonemes_dtw("dɪs", "ðɪs") error_types = [r["error_type"] for r in results] assert "substitution" in error_types, ( f"/ð/ → /d/ phải là substitution, got {error_types}" ) # Tìm đúng cặp sub = next((r for r in results if r["error_type"] == "substitution"), None) assert sub is not None assert sub["phoneme_expected"] == "ð", f"Expected /ð/ but got {sub['phoneme_expected']}" assert sub["phoneme_actual"] == "d", f"Expected actual /d/ but got {sub['phoneme_actual']}"
def test_align_empty_actual(): """Actual IPA rỗng → tất cả là deletion.""" results = align_phonemes_dtw("N/A", "kæt") assert all(r["error_type"] == "deletion" for r in results), ( f"Empty actual phải all deletion, got {[r['error_type'] for r in results]}" )
# ============================================================# TEST: compute_practice_score# ============================================================
def test_score_perfect(): """Perfect match → score ≥ 90.""" results = align_phonemes_dtw("kæt", "kæt") score = compute_practice_score(results) assert score >= 90, f"Perfect match phải ≥ 90, got {score}"
def test_score_with_deletion(): """Có deletion → score ≤ 90 (penalty -10/deletion).""" results = align_phonemes_dtw("ˈstjuːdən", "ˈstjuːdənt") score = compute_practice_score(results) # 1 deletion = -10 điểm → score phải < 100 assert score < 100, f"Audio với deletion phải < 100, got {score}" assert score <= 90, f"Audio với deletion phải ≤ 90, got {score}"
def test_score_clamp_zero(): """Nhiều lỗi → score không âm.""" bad_results = [ {"error_type": "deletion", "is_correct": False}, {"error_type": "deletion", "is_correct": False}, {"error_type": "substitution", "is_correct": False}, {"error_type": "substitution", "is_correct": False}, {"error_type": "substitution", "is_correct": False}, {"error_type": "insertion", "is_correct": False}, {"error_type": "deletion", "is_correct": False}, {"error_type": "deletion", "is_correct": False}, {"error_type": "deletion", "is_correct": False}, {"error_type": "deletion", "is_correct": False}, ] score = compute_practice_score(bad_results) assert score >= 0, f"Score không được âm, got {score}"
def test_score_no_errors(): """Không lỗi nào → 100.""" good = [{"error_type": "correct", "is_correct": True} for _ in range(5)] assert compute_practice_score(good) == 100
# ============================================================# TEST: generate_rule_feedback# ============================================================
def test_feedback_perfect(): """Không lỗi → feedback tích cực.""" results = [{"error_type": "correct", "is_correct": True, "phoneme_expected": "k", "phoneme_actual": "k"} for _ in range(3)] summary = {"correct": 3, "deletion": 0, "substitution": 0, "insertion": 0, "stress_error": 0} fb = generate_rule_feedback(summary, results) assert "Tuyệt" in fb or "tuyệt" in fb or "chuẩn" in fb, \ f"Perfect feedback phải tích cực, got: {fb}"
def test_feedback_deletion(): """Có deletion → feedback mention âm bị nuốt.""" results = [ {"error_type": "deletion", "is_correct": False, "phoneme_expected": "t", "phoneme_actual": None}, ] summary = {"correct": 5, "deletion": 1, "substitution": 0, "insertion": 0, "stress_error": 0} fb = generate_rule_feedback(summary, results) assert "/t/" in fb, f"Deletion feedback phải mention /t/, got: {fb}" assert "nuốt" in fb.lower(), f"Deletion feedback phải mention 'nuốt', got: {fb}"
def test_feedback_substitution(): """Substitution → feedback mention cả 2 phoneme.""" results = [ {"error_type": "substitution", "is_correct": False, "phoneme_expected": "ð", "phoneme_actual": "d"}, ] summary = {"correct": 4, "deletion": 0, "substitution": 1, "insertion": 0, "stress_error": 0} fb = generate_rule_feedback(summary, results) assert "/d/" in fb and "/ð/" in fb, f"Substitution feedback phải mention cả /d/ và /ð/, got: {fb}"
def test_feedback_max_5_items(): """Nhiều lỗi → tối đa 5 điểm được liệt kê.""" results = [ {"error_type": "deletion", "is_correct": False, "phoneme_expected": f"p{i}", "phoneme_actual": None} for i in range(10) ] summary = {"correct": 0, "deletion": 10, "substitution": 0, "insertion": 0, "stress_error": 0} fb = generate_rule_feedback(summary, results) # Đếm bullets bullet_count = fb.count("•") assert bullet_count <= 5, f"Feedback phải có ≤ 5 bullets, got {bullet_count}"
# ============================================================# Main runner# ============================================================if __name__ == "__main__": import pytest pytest.main([__file__, "-v"])123457 unmodified lines1314151617181920212223171 unmodified lines195196197198199200157 unmodified lines358359360361362363import uvicornfrom fastapi import FastAPI, HTTPException, UploadFile, File, Formfrom pydantic import BaseModel, Fieldfrom transformers import pipelineimport torch7 unmodified linesfrom dotenv import load_dotenvfrom typing import Optional, Listimport uuidtry:from src.pronunciation import grade_pronunciation_advancedexcept ImportError:from pronunciation import grade_pronunciation_advancedload_dotenv()171 unmodified linesresp = await client.post(OPENAI_API_URL, headers={"Authorization": f"Bearer {OPENAI_API_KEY}"}, json=payload)return json.loads(resp.json()['choices'][0]['message']['content'])app = FastAPI(title="IELTS Full-Stack AI API (V15.0)")@app.post("/grade/writing", response_model=WritingResponse)157 unmodified linesfinally:if os.path.exists(temp_filename): os.remove(temp_filename)@app.get("/")def read_root():return {"message": "IELTS API is running."}123457 unmodified lines1314151617181920212223242526272829303132333435363738171 unmodified lines210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273157 unmodified lines431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567import uvicornfrom fastapi import FastAPI, HTTPException, UploadFile, File, Form, Requestfrom pydantic import BaseModel, Fieldfrom transformers import pipelineimport torch7 unmodified linesfrom dotenv import load_dotenvfrom typing import Optional, Listimport uuidimport timeimport tracebackfrom collections import defaultdicttry:from src.pronunciation import (grade_pronunciation_advanced,align_phonemes_dtw,compute_practice_score,generate_rule_feedback,analyze_sentence_stress,)except ImportError:from pronunciation import (grade_pronunciation_advanced,align_phonemes_dtw,compute_practice_score,generate_rule_feedback,analyze_sentence_stress,)load_dotenv()171 unmodified linesresp = await client.post(OPENAI_API_URL, headers={"Authorization": f"Bearer {OPENAI_API_KEY}"}, json=payload)return json.loads(resp.json()['choices'][0]['message']['content'])# ============================================================# RATE LIMITER — AI Microservice Layer# Sliding window per IP: tối đa 30 req/min cho practice endpoint# ============================================================_RATE_LIMIT_WINDOW_SEC = 60_RATE_LIMIT_MAX_REQUESTS = 30_rate_limit_store: dict[str, list[float]] = defaultdict(list)def _check_rate_limit(client_ip: str) -> None:"""Raise HTTP 429 nếu IP vượt quá giới hạn trong cửa sổ 60 giây."""now = time.time()window_start = now - _RATE_LIMIT_WINDOW_SECtimestamps = _rate_limit_store[client_ip]# Xóa timestamps cũ_rate_limit_store[client_ip] = [t for t in timestamps if t > window_start]if len(_rate_limit_store[client_ip]) >= _RATE_LIMIT_MAX_REQUESTS:raise HTTPException(status_code=429,detail="Quá nhiều yêu cầu. Vui lòng thử lại sau 60 giây.")_rate_limit_store[client_ip].append(now)# ============================================================# PYDANTIC SCHEMAS — 7-Component Pronunciation Practice# ============================================================class PhonemeResult(BaseModel):phoneme_expected: Optional[str] = Nonephoneme_actual: Optional[str] = Noneis_correct: boolerror_type: str # correct / substitution / deletion / insertion / stress_errorconfidence: float # 0.0 – 1.0class ComponentScores(BaseModel):individual_sounds: int # 0-100 (luôn có)word_stress: int # 0-100 (luôn có)sentence_stress: Optional[int] = None # 0-100 (chỉ sentence)linking: Optional[int] = None # 0-100 (chỉ sentence/phrase)intonation: Optional[int] = None # 0-100 (chỉ sentence/phrase)chunking: Optional[int] = None # 0-100 (chỉ sentence)contracted_words: int = 100 # 0-100 (luôn có)class PronunciationPracticeResult(BaseModel):target: strtarget_type: str # word / phrase / sentence / ipatarget_ipa: stractual_ipa: stroverall_score: int # 0-100 WEIGHTED final scorecomponent_scores: ComponentScores # breakdown 7 thành phầnphoneme_results: List[PhonemeResult] # DTW alignment detailserror_summary: dict # {deletion:N, substitution:N, ...}feedback_text: str # Multi-section feedback tiếng Việtweights_used: dict # Trọng số đã dùngprocessing_time_ms: intapp = FastAPI(title="IELTS Full-Stack AI API (V15.0)")@app.post("/grade/writing", response_model=WritingResponse)157 unmodified linesfinally:if os.path.exists(temp_filename): os.remove(temp_filename)@app.post("/grade/pronunciation/practice", response_model=PronunciationPracticeResult)async def grade_pronunciation_practice(request: Request,audio: UploadFile = File(...),target: str = Form(...),target_type: str = Form("word"),):"""7-Component Pronunciation Assessment.Components:1. Individual Sounds (Âm vị) — Wav2Vec2 + DTW2. Word Stress (Trọng âm từ) — F0 per-syllable3. Sentence Stress (Trọng âm câu) — F0 peaks4. Linking (Nối âm) — Rule-based IPA boundaries5. Intonation (Ngữ điệu) — F0 contour shape6. Chunking (Chia đoạn) — Pause/breath groups7. Contracted Words (Từ rút gọn) — Dict lookupWeights:- word: individual_sounds 60% + word_stress 35% + contracted_words 5%- phrase: individual_sounds 35% + word_stress 20% + linking 25% + intonation 10% + contracted_words 10%- sentence: individual_sounds 30% + word_stress 20% + sentence_stress 15% + linking 15% + intonation 10% + chunking 5% + contracted_words 5%"""# Rate limit: 30 req/min per IPclient_ip = request.client.host if request.client else "unknown"_check_rate_limit(client_ip)# Validate target_typeallowed_types = {"word", "phrase", "sentence", "ipa"}if target_type not in allowed_types:raise HTTPException(status_code=422,detail=f"target_type phải là một trong: {allowed_types}")if not target or not target.strip():raise HTTPException(status_code=422, detail="target không được để trống.")start_ms = time.time()temp_filename = f"temp_practice_{uuid.uuid4()}.wav"try:# Lưu file tạmwith open(temp_filename, "wb") as buffer:shutil.copyfileobj(audio.file, buffer)file_size = os.path.getsize(temp_filename)if file_size == 0:raise HTTPException(status_code=422, detail="File audio trống.")# Import scorer (lazy để tránh circular import)try:from src.pronunciation_analysis.scorer import run_full_assessmentexcept ImportError:from pronunciation_analysis.scorer import run_full_assessment# Chạy 7-component assessmentresult = run_full_assessment(audio_path=temp_filename,target_text=target,target_type=target_type,)# Extract phoneme results (Component 1 details)c1 = result.components.get("individual_sounds")raw_results = c1.details if c1 else []# Error summary từ phoneme resultserror_summary: dict[str, int] = {"correct": 0, "deletion": 0, "substitution": 0,"insertion": 0, "stress_error": 0,}for r in raw_results:et = r.get("error_type", "correct")error_summary[et] = error_summary.get(et, 0) + 1# Component scorescs = result.component_scorescomponent_scores = ComponentScores(individual_sounds=cs.get("individual_sounds", 0) or 0,word_stress=cs.get("word_stress", 0) or 0,sentence_stress=cs.get("sentence_stress"),linking=cs.get("linking"),intonation=cs.get("intonation"),chunking=cs.get("chunking"),contracted_words=cs.get("contracted_words", 100) or 100,)# IPA strings (từ Component 1)ipa_data = grade_pronunciation_advanced(temp_filename, target)actual_ipa = ipa_data.get("actual_ipa", "N/A")expected_ipa = ipa_data.get("expected_ipa", "N/A")processing_time_ms = int((time.time() - start_ms) * 1000)return PronunciationPracticeResult(target=target,target_type=target_type,target_ipa=expected_ipa,actual_ipa=actual_ipa,overall_score=result.overall_score,component_scores=component_scores,phoneme_results=[PhonemeResult(phoneme_expected=r.get("phoneme_expected"),phoneme_actual=r.get("phoneme_actual"),is_correct=r.get("is_correct", False),error_type=r.get("error_type", "correct"),confidence=r.get("confidence", 0.0),)for r in raw_results],error_summary=error_summary,feedback_text=result.feedback_text,weights_used=result.weights_used,processing_time_ms=processing_time_ms,)except HTTPException:raiseexcept Exception as e:print(f"Practice Pronunciation Error: {e}")traceback.print_exc()raise HTTPException(status_code=500, detail=str(e))finally:if os.path.exists(temp_filename):os.remove(temp_filename)@app.get("/")def read_root():return {"message": "IELTS API is running."}
1 unmodified line23456789101196 unmodified lines1081091101111 unmodified lineimport librosaimport numpy as npimport osimport tracebackimport subprocessimport shutilfrom transformers import (Wav2Vec2ForCTC,AutoTokenizer,96 unmodified linesreturn {"actual_ipa": actual_ipa,"expected_ipa": expected_ipa}1 unmodified line2345678910111296 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626631 unmodified lineimport librosaimport numpy as npimport osimport reimport tracebackimport subprocessimport shutilfrom typing import Optionalfrom transformers import (Wav2Vec2ForCTC,AutoTokenizer,96 unmodified linesreturn {"actual_ipa": actual_ipa,"expected_ipa": expected_ipa}# ============================================================# F0 PITCH-BASED SENTENCE STRESS ANALYSIS (Parselmouth/Praat)# Chạy song song với DTW phoneme engine.# Chỉ có nghĩa với target_type="sentence" (≥ 3 syllables).# ============================================================try:import parselmouthfrom parselmouth.praat import call as praat_call_PARSELMOUTH_AVAILABLE = Trueprint("Parselmouth available: sentence stress analysis enabled.")except ImportError:_PARSELMOUTH_AVAILABLE = Falseprint("WARNING: praat-parselmouth not installed. Sentence stress analysis disabled.")def _extract_f0_peaks(audio_path: str) -> list[float]:"""Trả về list F0 (Hz) tại mỗi voiced frame (20ms hop).Unvoiced frames (silence/consonants) → 0.0."""if not _PARSELMOUTH_AVAILABLE:return []try:sound = parselmouth.Sound(audio_path)pitch = praat_call(sound, "To Pitch", 0.0, 75.0, 600.0)n_frames = praat_call(pitch, "Get number of frames")f0_values: list[float] = []for i in range(1, int(n_frames) + 1):v = praat_call(pitch, "Get value in frame", i, "Hertz")f0_values.append(float(v) if v == v else 0.0) # NaN → 0.0return f0_valuesexcept Exception as e:print(f"F0 extraction error: {e}")return []def _get_expected_stress_positions(expected_ipa: str) -> list[int]:"""Trả về list vị trí (index trong phoneme sequence) được đánh dấustress (ˈ primary, ˌ secondary) trong eSpeak IPA output."""tokens = tokenize_ipa(expected_ipa)stressed: list[int] = []phoneme_idx = 0for tok in tokens:if tok in ("ˈ", "ˌ"):# Phoneme tiếp theo (index phoneme_idx) là stressedstressed.append(phoneme_idx)else:phoneme_idx += 1return stresseddef analyze_sentence_stress(audio_path: str,expected_ipa: str,target_type: str = "sentence",) -> dict:"""Phân tích trọng âm câu bằng F0 pitch từ audio.Returns:{"sentence_stress_score": int 0-100, # 100 = perfect stress pattern"stress_details": list[dict], # chi tiết từng vị trí stressed"f0_analysis_available": bool,"warning": str | None, # lý do nếu không thể phân tích}"""# Chỉ phân tích khi target_type = sentence và parselmouth có sẵnif target_type != "sentence":return {"sentence_stress_score": None,"stress_details": [],"f0_analysis_available": False,"warning": "Sentence stress analysis chỉ áp dụng cho target_type='sentence'.",}if not _PARSELMOUTH_AVAILABLE:return {"sentence_stress_score": None,"stress_details": [],"f0_analysis_available": False,"warning": "praat-parselmouth chưa được cài đặt.",}try:# 1. Extract F0 frames (20ms mỗi frame)f0_frames = _extract_f0_peaks(audio_path)if not f0_frames:return {"sentence_stress_score": None,"stress_details": [],"f0_analysis_available": False,"warning": "Không trích xuất được F0 từ audio.",}# 2. Voiced frames = F0 > 0; lấy voiced segmentsvoiced = [(i, v) for i, v in enumerate(f0_frames) if v > 0]if not voiced:return {"sentence_stress_score": 50, # Không đủ dữ liệu → neutral score"stress_details": [],"f0_analysis_available": True,"warning": "Không phát hiện được voiced segments đủ để phân tích pitch.",}# 3. Phân chia voiced frames thành syllable-like chunks# Heuristic: nhóm voiced frames liên tục, ngắt tại unvoiced gaps ≥ 50ms (≥ 2.5 frames)FRAME_DURATION_MS = 20GAP_THRESHOLD_FRAMES = 3 # 60ms gap → word/syllable boundarysyllable_groups: list[list[tuple[int, float]]] = []current_group: list[tuple[int, float]] = []prev_idx = -99for idx, val in voiced:if current_group and idx - prev_idx > GAP_THRESHOLD_FRAMES:syllable_groups.append(current_group)current_group = []current_group.append((idx, val))prev_idx = idxif current_group:syllable_groups.append(current_group)if not syllable_groups:return {"sentence_stress_score": 50,"stress_details": [],"f0_analysis_available": True,"warning": "Không đủ voiced segments để phân tích.",}# 4. Tính F0 trung bình mỗi syllable groupsyllable_f0: list[float] = [float(np.mean([v for _, v in grp])) for grp in syllable_groups]# 5. Normalize F0 về 0-1 trong audio này (loại bỏ speaker pitch variation)f0_max = max(syllable_f0)f0_min = min(syllable_f0)f0_range = f0_max - f0_min if f0_max > f0_min else 1.0f0_norm = [(v - f0_min) / f0_range for v in syllable_f0]# 6. Lấy expected stress positions từ eSpeak IPAexpected_stress_idx = _get_expected_stress_positions(expected_ipa)n_syllables = len(syllable_groups)# 7. Map expected stress positions → syllable groups (best effort)# eSpeak stress index → syllable group index (proportion-based)n_expected_phonemes = max(expected_stress_idx) + 1 if expected_stress_idx else 0stress_details: list[dict] = []matched = 0total_stressed = len(expected_stress_idx)for stress_phoneme_pos in expected_stress_idx:# Map phoneme position → syllable group index (linear interpolation)ratio = stress_phoneme_pos / max(n_expected_phonemes - 1, 1)syl_idx = min(int(ratio * n_syllables), n_syllables - 1)f0_at_stress = f0_norm[syl_idx]# Stressed syllable nên có F0 tương đối cao (> 0.4 normalized)# và nên là local maximum trong nhóm lân cậnSTRESS_F0_THRESHOLD = 0.4is_stressed_correctly = f0_at_stress >= STRESS_F0_THRESHOLD# Kiểm tra local maximum (so với ± 1 syllable)neighbors = [f0_norm[max(0, syl_idx - 1)],f0_norm[min(n_syllables - 1, syl_idx + 1)],]is_local_peak = f0_at_stress >= max(neighbors) * 0.85correct = is_stressed_correctly or is_local_peakif correct:matched += 1stress_details.append({"expected_phoneme_idx": stress_phoneme_pos,"syllable_group_idx": syl_idx,"f0_normalized": round(f0_at_stress, 3),"is_correctly_stressed": correct,})# 8. Tính sentence_stress_scoreif total_stressed == 0:sentence_stress_score = 100 # Không có stress trong expected → auto passelse:accuracy = matched / total_stressed# Scale: 100 khi perfect, 50 khi 0% match (không phạt quá nặng)sentence_stress_score = int(50 + accuracy * 50)return {"sentence_stress_score": sentence_stress_score,"stress_details": stress_details,"f0_analysis_available": True,"warning": None,}except Exception as e:print(f"Sentence stress analysis error: {e}")return {"sentence_stress_score": None,"stress_details": [],"f0_analysis_available": False,"warning": f"Lỗi phân tích: {str(e)}",}# Bảng đặc trưng IPA feature (place, manner, voicing).# Mỗi phoneme → vector [place(0-7), manner(0-5), voiced(0/1)]# place: 0=bilabial,1=labiodental,2=dental,3=alveolar,4=postalveolar,# 5=palatal,6=velar,7=glottal; -1=vowel# manner: 0=stop,1=fricative,2=affricate,3=nasal,4=lateral,5=approximant; -1=vowel# voiced: 0=voiceless, 1=voiced; -1=N/A(vowel)_IPA_FEATURES: dict[str, tuple] = {# --------- CONSONANTS ---------# Stops"p": (0, 0, 0), "b": (0, 0, 1),"t": (3, 0, 0), "d": (3, 0, 1),"k": (6, 0, 0), "ɡ": (6, 0, 1), "g": (6, 0, 1),"ʔ": (7, 0, 0),# Fricatives"f": (1, 1, 0), "v": (1, 1, 1),"θ": (2, 1, 0), "ð": (2, 1, 1),"s": (3, 1, 0), "z": (3, 1, 1),"ʃ": (4, 1, 0), "ʒ": (4, 1, 1),"h": (7, 1, 0),# Affricates"tʃ": (4, 2, 0), "dʒ": (4, 2, 1),"t͡ʃ": (4, 2, 0), "d͡ʒ": (4, 2, 1),# Nasals"m": (0, 3, 1), "n": (3, 3, 1), "ŋ": (6, 3, 1),# Laterals & Approximants"l": (3, 4, 1), "r": (3, 5, 1), "ɹ": (3, 5, 1),"j": (5, 5, 1), "w": (0, 5, 1),# --------- VOWELS (place=-1, manner=-1, voiced=-1) ---------"iː": (-1, -1, -1), "ɪ": (-1, -1, -1),"eɪ": (-1, -1, -1), "ɛ": (-1, -1, -1), "e": (-1, -1, -1),"æ": (-1, -1, -1),"ɑː": (-1, -1, -1), "ɑ": (-1, -1, -1),"ɒ": (-1, -1, -1), "ɔː": (-1, -1, -1), "ɔ": (-1, -1, -1),"oʊ": (-1, -1, -1), "ɔɪ": (-1, -1, -1),"ʊ": (-1, -1, -1), "uː": (-1, -1, -1),"aɪ": (-1, -1, -1), "aʊ": (-1, -1, -1),"ə": (-1, -1, -1), "ɜː": (-1, -1, -1), "ɜ": (-1, -1, -1),"ʌ": (-1, -1, -1),"ɪə": (-1, -1, -1), "eə": (-1, -1, -1), "ʊə": (-1, -1, -1),}# Weights cho từng feature dimension khi tính distance# place (0.5) > manner (0.35) > voicing (0.15) — voicing là feature dễ nhầm nhất_FEATURE_WEIGHTS = (0.5, 0.35, 0.15) # place, manner, voicingdef _ipa_feature_distance(p1: str, p2: str) -> float:"""Tính IPA feature-based distance giữa 2 phoneme (0.0 = giống nhau, 1.0 = khác hoàn toàn).Dùng weighted Euclidean distance trên không gian [place, manner, voiced]."""if p1 == p2:return 0.0f1 = _IPA_FEATURES.get(p1)f2 = _IPA_FEATURES.get(p2)# Nếu 1 trong 2 không biết → max distanceif f1 is None or f2 is None:return 1.0# Cả 2 là vowel → distance nhỏ hơn consonant mismatchif f1[0] == -1 and f2[0] == -1:return 0.3# 1 vowel 1 consonant → gần maxif (f1[0] == -1) != (f2[0] == -1):return 0.9# Cả 2 consonant → tính weighted feature distancetotal = 0.0ranges = (7.0, 5.0, 1.0) # max value mỗi dimension để normalizefor i, (a, b, w) in enumerate(zip(f1, f2, _FEATURE_WEIGHTS)):total += w * (abs(a - b) / ranges[i])return min(total, 1.0)# IPA tokenizer regex — ưu tiên polyphthong & affricate dài hơn trước_IPA_TOKEN_PATTERN = re.compile(r"(t͡ʃ|d͡ʒ|tʃ|dʒ" # affricates (multi-char first)r"|iː|ɑː|ɔː|uː|ɜː" # long vowelsr"|eɪ|aɪ|ɔɪ|aʊ|oʊ" # diphthongsr"|ɪə|eə|ʊə" # centering diphthongsr"|ˈ|ˌ" # stress marksr"|[a-zæðŋɑɒɔəɛɜɪʊʌʍʔθʃʒɹɡɲβçħɫɬɱɳɴɻʂʈ]" # single IPA charsr")")def tokenize_ipa(ipa_string: str) -> list[str]:"""Tách chuỗi IPA thành list phoneme tokens (bao gồm stress marks)."""if not ipa_string or ipa_string in ("N/A", "Error"):return []# Chuẩn hoá: bỏ space thừa, giữ stresscleaned = ipa_string.strip()return _IPA_TOKEN_PATTERN.findall(cleaned)def align_phonemes_dtw(actual_ipa_str: str, expected_ipa_str: str) -> list[dict]:"""DTW alignment giữa actual IPA và expected IPA.Trả về list[dict] mỗi phần tử mô tả một cặp phoneme alignment.Returns:list of {phoneme_expected: str | None,phoneme_actual: str | None,is_correct: bool,error_type: "correct" | "substitution" | "deletion" | "insertion" | "stress_error",confidence: float # 1 - distance}"""actual_tokens = tokenize_ipa(actual_ipa_str)expected_tokens = tokenize_ipa(expected_ipa_str)if not expected_tokens:return []if not actual_tokens:# Mọi expected phoneme đều là deletionreturn [{"phoneme_expected": e,"phoneme_actual": None,"is_correct": False,"error_type": "deletion","confidence": 0.0,}for e in expected_tokensif e not in ("ˈ", "ˌ") # skip stress marks ở đây, xử lý riêng]# Tách stress marks để xử lý riêng_STRESS = {"ˈ", "ˌ"}expected_stressed: set[int] = set()expected_clean: list[str] = []for tok in expected_tokens:if tok in _STRESS:# Đánh dấu phoneme liền sau là có stressif expected_clean:expected_stressed.add(len(expected_clean) - 1)else:expected_clean.append(tok)actual_stressed: set[int] = set()actual_clean: list[str] = []for tok in actual_tokens:if tok in _STRESS:if actual_clean:actual_stressed.add(len(actual_clean) - 1)else:actual_clean.append(tok)N, M = len(actual_clean), len(expected_clean)# Build DTW cost matrixINF = float("inf")dtw = np.full((N + 1, M + 1), INF)dtw[0, 0] = 0.0for i in range(1, N + 1):dtw[i, 0] = INF # insertion penalty accumulationfor j in range(1, M + 1):dtw[0, j] = INF # deletion penalty accumulation# Cho phép bắt đầu matching từ bất kỳ điểm nào → dùng 0.0 ở hàng 0dtw[0, :] = 0.0for i in range(1, N + 1):for j in range(1, M + 1):cost = _ipa_feature_distance(actual_clean[i - 1], expected_clean[j - 1])dtw[i, j] = cost + min(dtw[i - 1, j - 1], # match/substitutiondtw[i - 1, j], # insertion (extra actual phoneme)dtw[i, j - 1], # deletion (missing actual phoneme))# Backtrack để tìm alignment pathalignment: list[tuple[Optional[int], Optional[int]]] = []i, j = N, Mwhile i > 0 or j > 0:if i == 0:alignment.append((None, j - 1))j -= 1elif j == 0:alignment.append((i - 1, None))i -= 1else:match = dtw[i - 1, j - 1]insert = dtw[i - 1, j]delete = dtw[i, j - 1]best = min(match, insert, delete)if best == match:alignment.append((i - 1, j - 1))i -= 1; j -= 1elif best == insert:alignment.append((i - 1, None))i -= 1else:alignment.append((None, j - 1))j -= 1alignment.reverse()# Build resultsresults: list[dict] = []for (ai, ei) in alignment:a_phone = actual_clean[ai] if ai is not None else Nonee_phone = expected_clean[ei] if ei is not None else Noneif ai is None:# Expected phoneme bị thiếu trong actual → deletionresults.append({"phoneme_expected": e_phone,"phoneme_actual": None,"is_correct": False,"error_type": "deletion","confidence": 0.0,})elif ei is None:# Actual có phoneme thừa → insertionresults.append({"phoneme_expected": None,"phoneme_actual": a_phone,"is_correct": False,"error_type": "insertion","confidence": 0.0,})else:dist = _ipa_feature_distance(a_phone, e_phone)confidence = round(1.0 - dist, 3)# Kiểm tra stress error: expected có stress nhưng actual không (hoặc ngược lại)a_has_stress = ai in actual_stressede_has_stress = ei in expected_stressedis_stress_err = a_has_stress != e_has_stressif dist == 0.0 and not is_stress_err:results.append({"phoneme_expected": e_phone,"phoneme_actual": a_phone,"is_correct": True,"error_type": "correct","confidence": 1.0,})elif is_stress_err and dist == 0.0:results.append({"phoneme_expected": e_phone,"phoneme_actual": a_phone,"is_correct": False,"error_type": "stress_error","confidence": confidence,})else:results.append({"phoneme_expected": e_phone,"phoneme_actual": a_phone,"is_correct": False,"error_type": "substitution","confidence": confidence,})return resultsdef compute_practice_score(phoneme_results: list[dict]) -> int:"""Tính điểm 0-100 từ kết quả DTW alignment.Penalties:- deletion: -10 mỗi lần- substitution: -8 mỗi lần- insertion: -4 mỗi lần- stress_error: -5 mỗi lần"""PENALTY = {"deletion": 10,"substitution": 8,"insertion": 4,"stress_error": 5,}score = 100for r in phoneme_results:score -= PENALTY.get(r.get("error_type", "correct"), 0)return max(0, min(100, score))def generate_rule_feedback(error_summary: dict, phoneme_results: list[dict]) -> str:"""Sinh feedback tiếng Việt dựa trên rule theo loại lỗi.Ưu tiên 5 lỗi đầu tiên quan trọng nhất (theo penalty)."""PRIORITY_ORDER = ["deletion", "substitution", "stress_error", "insertion"]# Gom lỗi theo loạierrors_by_type: dict[str, list[dict]] = {t: [] for t in PRIORITY_ORDER}for r in phoneme_results:et = r.get("error_type", "correct")if et in errors_by_type:errors_by_type[et].append(r)feedback_lines: list[str] = []MAX_ITEMS = 5count = 0for error_type in PRIORITY_ORDER:for r in errors_by_type[error_type]:if count >= MAX_ITEMS:breakep = r.get("phoneme_expected") or ""ap = r.get("phoneme_actual") or ""if error_type == "deletion":line = f"• Bạn nuốt âm /{ep}/ (âm bị thiếu). Hãy chú ý phát âm rõ âm này."elif error_type == "substitution":line = f"• Bạn đọc /{ap}/ thay vì /{ep}/. Kiểm tra vị trí lưỡi và hình miệng khi phát âm /{ep}/."elif error_type == "stress_error":line = f"• Sai trọng âm tại /{ep}/. Hãy nhấn mạnh hơn (hoặc nhẹ hơn) vào âm tiết này."elif error_type == "insertion":line = f"• Bạn thêm âm /{ap}/ không cần thiết. Bỏ âm này khi phát âm."else:continuefeedback_lines.append(line)count += 1if count >= MAX_ITEMS:breaktotal_errors = sum(len(v) for v in errors_by_type.values())if not feedback_lines:return "Tuyệt vời! Phát âm của bạn rất chuẩn. Hãy tiếp tục luyện tập để duy trì."intro = f"Phát hiện {total_errors} lỗi phát âm. Một số điểm cần cải thiện:\n"outro = "\nHãy luyện tập chậm từng âm một trước khi nói liên tục."return intro + "\n".join(feedback_lines) + outro
123456789101112131415161718192021222324252627"""7-Component Pronunciation Analysis PackageChuẩn IELTS Pronunciation Assessment.
Components: 1. individual_sounds — Phoneme-level DTW alignment (30%) 2. word_stress — F0 per-syllable analysis (20%) 3. sentence_stress — F0 peak stress mapping (15%) 4. linking — Connected speech rules (15%) 5. intonation — F0 contour shape (10%) 6. chunking — Pause/breath groups (5%) 7. contracted_words — Contraction detection (5%)"""
from dataclasses import dataclass, fieldfrom typing import Optional
@dataclassclass ComponentResult: """Kết quả chuẩn hoá cho mỗi component.""" name: str score: int # 0-100 details: list[dict] = field(default_factory=list) feedback: str = "" available: bool = True warning: Optional[str] = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209"""Component 6: Chunking / Rhythm (Chia đoạn) — Weight 5%Kiểm tra pause/breath groups tại clause boundaries.Chỉ áp dụng cho target_type="sentence"."""
import reimport numpy as npfrom . import ComponentResult
def _detect_clause_boundaries(target_text: str) -> list[int]: """ Detect vị trí word index nên có pause (clause boundary). Dựa trên dấu câu: , ; : — ( ) """ words = target_text.strip().split() boundaries = [] for i, word in enumerate(words): if any(word.endswith(p) for p in [",", ";", ":", "—", ")", "]"]): boundaries.append(i) # Pause SAU word này return boundaries
def _detect_actual_pauses(audio_path: str, min_pause_sec: float = 0.15) -> list[dict]: """ Detect pauses (silence gaps) trong audio dùng librosa.
Returns: list[{"start": float, "end": float, "duration": float}] """ try: import librosa y, sr = librosa.load(audio_path, sr=16000) duration = librosa.get_duration(y=y, sr=sr)
# Non-silent intervals (inverted = pauses) intervals = librosa.effects.split(y, top_db=35) if len(intervals) == 0: return []
pauses = [] for i in range(len(intervals) - 1): gap_start = intervals[i][1] / sr gap_end = intervals[i + 1][0] / sr gap_dur = gap_end - gap_start if gap_dur >= min_pause_sec: pauses.append({ "start": round(gap_start, 3), "end": round(gap_end, 3), "duration": round(gap_dur, 3), })
return pauses
except Exception as e: print(f"Pause detection error: {e}") return []
def _analyze_speech_rate(audio_path: str, total_words: int) -> dict: """ Đánh giá tốc độ nói (words per minute). """ try: import librosa y, sr = librosa.load(audio_path, sr=16000) duration = librosa.get_duration(y=y, sr=sr)
if duration <= 0: return {"wpm": 0, "rating": "unknown", "penalty": 0}
wpm = (total_words / duration) * 60
# IELTS speaking: normal range ~120-160 WPM if wpm < 80: return {"wpm": round(wpm), "rating": "too_slow", "penalty": 15} elif wpm < 120: return {"wpm": round(wpm), "rating": "slightly_slow", "penalty": 5} elif wpm <= 180: return {"wpm": round(wpm), "rating": "normal", "penalty": 0} elif wpm <= 220: return {"wpm": round(wpm), "rating": "slightly_fast", "penalty": 5} else: return {"wpm": round(wpm), "rating": "too_fast", "penalty": 15}
except Exception as e: print(f"Speech rate error: {e}") return {"wpm": 0, "rating": "error", "penalty": 0}
def analyze( audio_path: str, target_text: str, target_type: str = "sentence",) -> ComponentResult: """ Phân tích chunking (chia đoạn, ngắt nhịp). Kiểm tra: meaningful pauses, speech rate. """ if target_type == "word": return ComponentResult( name="chunking", score=100, available=False, feedback="", warning="Chunking chỉ áp dụng cho câu.", )
words = target_text.strip().split() n_words = len(words)
if n_words <= 3: return ComponentResult( name="chunking", score=100, feedback="Câu ngắn — không cần kiểm tra chunking.", )
try: # 1. Detect expected clause boundaries expected_boundaries = _detect_clause_boundaries(target_text)
# 2. Detect actual pauses actual_pauses = _detect_actual_pauses(audio_path)
# 3. Speech rate rate_info = _analyze_speech_rate(audio_path, n_words)
# 4. Scoring score = 100 details = []
# Check: nếu có expected boundaries, actual phải có pauses if expected_boundaries and not actual_pauses: score -= 20 details.append({ "issue": "no_pauses_at_boundaries", "expected_pause_after_word": [words[i] for i in expected_boundaries if i < n_words], })
# Check: nếu có expected boundaries, kiểm tra pause positions match # (simplified — proportional position matching) if expected_boundaries and actual_pauses: import librosa y, sr = librosa.load(audio_path, sr=16000) duration = librosa.get_duration(y=y, sr=sr)
matched = 0 for b_idx in expected_boundaries: expected_ratio = (b_idx + 1) / n_words expected_time = expected_ratio * duration
# Tìm pause gần nhất closest = min(actual_pauses, key=lambda p: abs(p["start"] - expected_time)) if abs(closest["start"] - expected_time) < duration * 0.15: matched += 1
boundary_accuracy = matched / len(expected_boundaries) if expected_boundaries else 1.0 score = max(score - int((1 - boundary_accuracy) * 30), score - 30) details.append({ "expected_boundaries": len(expected_boundaries), "matched_pauses": matched, "boundary_accuracy": round(boundary_accuracy, 2), })
# Check: too many unnatural pauses (mid-word hesitations) if actual_pauses and n_words >= 5: expected_max_pauses = max(1, n_words // 4) if len(actual_pauses) > expected_max_pauses * 2: excess = len(actual_pauses) - expected_max_pauses score -= min(20, excess * 5) details.append({ "issue": "too_many_pauses", "actual_count": len(actual_pauses), "expected_max": expected_max_pauses, })
# Apply speech rate penalty score -= rate_info.get("penalty", 0) score = max(0, min(100, score))
details.append({"speech_rate": rate_info})
# Feedback feedback_parts = [] rating = rate_info.get("rating", "normal") if rating == "too_slow": feedback_parts.append("Tốc độ nói quá chậm, cần nói tự nhiên hơn.") elif rating == "too_fast": feedback_parts.append("Tốc độ nói quá nhanh, cần chậm lại để rõ ràng hơn.")
if expected_boundaries and not actual_pauses: feedback_parts.append("Thiếu ngắt nhịp tại dấu phẩy/dấu chấm phẩy.")
if not feedback_parts: feedback = "Chia đoạn và nhịp điệu tốt." else: feedback = " ".join(feedback_parts)
return ComponentResult( name="chunking", score=score, details=details, feedback=feedback, )
except Exception as e: print(f"Chunking analysis error: {e}") return ComponentResult( name="chunking", score=75, available=False, warning=str(e), feedback="Lỗi phân tích chunking.", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""Component 7: Contracted Words (Từ rút gọn) — Weight 5%Dict-based detection + IPA comparison."""
from . import ComponentResult
try: from src.pronunciation import tokenize_ipaexcept ImportError: from pronunciation import tokenize_ipa
# ============================================================# Contraction Dictionary# Format: {contracted_form: (full_form, register)}# register: "informal" (acceptable), "formal" (expected)# ============================================================CONTRACTIONS = { # Common contractions (acceptable in speech) "i'm": ("i am", "informal"), "i'll": ("i will", "informal"), "i've": ("i have", "informal"), "i'd": ("i would", "informal"), "you're": ("you are", "informal"), "you'll": ("you will", "informal"), "you've": ("you have", "informal"), "you'd": ("you would", "informal"), "he's": ("he is", "informal"), "he'll": ("he will", "informal"), "he'd": ("he would", "informal"), "she's": ("she is", "informal"), "she'll": ("she will", "informal"), "she'd": ("she would", "informal"), "it's": ("it is", "informal"), "it'll": ("it will", "informal"), "we're": ("we are", "informal"), "we'll": ("we will", "informal"), "we've": ("we have", "informal"), "we'd": ("we would", "informal"), "they're": ("they are", "informal"), "they'll": ("they will", "informal"), "they've": ("they have", "informal"), "they'd": ("they would", "informal"), "that's": ("that is", "informal"), "there's": ("there is", "informal"), "here's": ("here is", "informal"), "what's": ("what is", "informal"), "who's": ("who is", "informal"), "where's": ("where is", "informal"), "when's": ("when is", "informal"), "how's": ("how is", "informal"), # Negative contractions "don't": ("do not", "informal"), "doesn't": ("does not", "informal"), "didn't": ("did not", "informal"), "isn't": ("is not", "informal"), "aren't": ("are not", "informal"), "wasn't": ("was not", "informal"), "weren't": ("were not", "informal"), "hasn't": ("has not", "informal"), "haven't": ("have not", "informal"), "hadn't": ("had not", "informal"), "won't": ("will not", "informal"), "wouldn't": ("would not", "informal"), "can't": ("cannot", "informal"), "couldn't": ("could not", "informal"), "shouldn't": ("should not", "informal"), "mustn't": ("must not", "informal"), "ain't": ("is not", "informal"), # Casual/slang contractions (may need correction in formal context) "gonna": ("going to", "casual"), "wanna": ("want to", "casual"), "gotta": ("got to", "casual"), "kinda": ("kind of", "casual"), "sorta": ("sort of", "casual"), "dunno": ("don't know", "casual"), "lemme": ("let me", "casual"), "gimme": ("give me", "casual"), "coulda": ("could have", "casual"), "shoulda": ("should have", "casual"), "woulda": ("would have", "casual"), "oughta": ("ought to", "casual"), "hafta": ("have to", "casual"), "outta": ("out of", "casual"), "lotsa": ("lots of", "casual"),}
# Reverse lookup: full form → contracted formFULL_TO_CONTRACTED = {}for contracted, (full, _) in CONTRACTIONS.items(): FULL_TO_CONTRACTED[full] = contracted
def _find_contractions_in_text(target_text: str) -> list[dict]: """ Tìm contractions trong target text.
Returns: list[{ "word": str, "position": int, # word index "full_form": str, "contracted_form": str, "register": str, }] """ words = target_text.lower().strip().split() found = []
for i, word in enumerate(words): clean = word.strip(".,!?;:'\"()[]") if clean in CONTRACTIONS: full_form, register = CONTRACTIONS[clean] found.append({ "word": clean, "position": i, "full_form": full_form, "contracted_form": clean, "register": register, "type": "contracted_in_target", }) # Check 2-word contractions (e.g., "going to" → "gonna") if i < len(words) - 1: bigram = f"{clean} {words[i + 1].strip('.,!?;:')}" if bigram in FULL_TO_CONTRACTED: found.append({ "word": bigram, "position": i, "full_form": bigram, "contracted_form": FULL_TO_CONTRACTED[bigram], "register": CONTRACTIONS[FULL_TO_CONTRACTED[bigram]][1], "type": "full_form_in_target", })
return found
def analyze( actual_ipa: str, target_text: str, target_type: str = "word",) -> ComponentResult: """ Phân tích từ rút gọn. - Nếu target có contraction: kiểm tra phát âm đúng dạng rút g���n - Nếu target có full form: kiểm tra người học có dùng contraction không """ contractions = _find_contractions_in_text(target_text)
if not contractions: return ComponentResult( name="contracted_words", score=100, feedback="Không có từ rút gọn cần kiểm tra.", )
details = [] score = 100
for c in contractions: if c["type"] == "contracted_in_target": # Target dùng contraction → phải phát âm đúng dạng rút gọn # Simplified: nếu actual IPA có đủ phonemes → OK details.append({ **c, "is_correct": True, # Lenient — DTW đã kiểm tra phonemes "note": "Contraction trong target — đã kiểm tra qua phoneme alignment.", }) elif c["type"] == "full_form_in_target": # Target dùng full form (e.g., "going to") # Nếu người nói dùng "gonna" → acceptable nhưng note if c["register"] == "casual": details.append({ **c, "is_correct": True, "note": f"'{c['full_form']}' — dạng rút gọn '{c['contracted_form']}' có thể dùng trong nói.", }) else: details.append({ **c, "is_correct": True, "note": f"'{c['full_form']}' — có thể nói '{c['contracted_form']}' tự nhiên.", })
wrong = [d for d in details if not d.get("is_correct", True)] if wrong: score = max(0, score - len(wrong) * 15)
if not wrong: feedback_parts = [] for d in details[:2]: w = d.get("word", "") feedback_parts.append(f"'{w}' OK") feedback = "Từ rút gọn: " + ", ".join(feedback_parts) + "." else: feedback = "Cần chú ý phát âm đúng dạng rút gọn."
return ComponentResult( name="contracted_words", score=score, details=details, feedback=feedback, )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Component 1: Individual Sounds (Âm vị) — Weight 30%Wrapper quanh DTW phoneme alignment engine đã có trong pronunciation.py."""
from . import ComponentResult
try: from src.pronunciation import ( align_phonemes_dtw, compute_practice_score, )except ImportError: from pronunciation import ( align_phonemes_dtw, compute_practice_score, )
def analyze(actual_ipa: str, expected_ipa: str) -> ComponentResult: """ Phân tích từng âm vị: substitution, deletion, insertion.
Returns: ComponentResult với score 0-100, details = list phoneme alignment results. """ results = align_phonemes_dtw(actual_ipa, expected_ipa) score = compute_practice_score(results)
# Sinh feedback tiếng Việt ngắn gọn cho component này errors = [r for r in results if r.get("error_type") != "correct"] if not errors: feedback = "Các âm vị được phát âm chính xác." else: lines = [] for r in errors[:3]: # Max 3 lỗi et = r.get("error_type", "") ep = r.get("phoneme_expected", "") ap = r.get("phoneme_actual", "") if et == "deletion": lines.append(f"Nuốt âm /{ep}/") elif et == "substitution": lines.append(f"/{ap}/ thay vì /{ep}/") elif et == "insertion": lines.append(f"Thêm âm /{ap}/ thừa") feedback = "Lỗi âm vị: " + "; ".join(lines) + "."
return ComponentResult( name="individual_sounds", score=score, details=results, feedback=feedback, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"""Component 5: Intonation (Ngữ điệu) — Weight 10%F0 contour shape analysis: rising/falling/flat.Chỉ áp dụng cho target_type="sentence"."""
import numpy as npfrom . import ComponentResult
try: from src.pronunciation import _extract_f0_peaks, _PARSELMOUTH_AVAILABLEexcept ImportError: from pronunciation import _extract_f0_peaks, _PARSELMOUTH_AVAILABLE
def _detect_expected_pattern(target_text: str) -> str: """ Xác định intonation pattern kỳ vọng từ punctuation. """ text = target_text.strip() if text.endswith("?"): # Yes/No question → rising; Wh-question → falling wh_words = {"what", "where", "when", "which", "who", "whom", "whose", "why", "how"} first_word = text.split()[0].lower().rstrip("?") if first_word in wh_words: return "falling" # Wh-question return "rising" # Yes/No question elif text.endswith("!"): return "falling" # Exclamation → strong falling elif text.endswith(","): return "rising" # Continuation → slight rising else: return "falling" # Statement → falling
def _analyze_f0_contour(f0_frames: list[float]) -> dict: """ Phân tích F0 contour shape.
Returns: { "actual_pattern": "rising" | "falling" | "flat", "f0_start": float, # F0 trung bình 30% đầu "f0_end": float, # F0 trung bình 30% cuối "f0_change_ratio": float, # (end - start) / start } """ voiced = [v for v in f0_frames if v > 0] if len(voiced) < 5: return { "actual_pattern": "flat", "f0_start": 0.0, "f0_end": 0.0, "f0_change_ratio": 0.0, }
# Lấy 30% đầu và 30% cuối n = len(voiced) segment = max(1, int(n * 0.3)) f0_start = float(np.mean(voiced[:segment])) f0_end = float(np.mean(voiced[-segment:]))
if f0_start == 0: ratio = 0.0 else: ratio = (f0_end - f0_start) / f0_start
# Thresholds RISE_THRESHOLD = 0.08 # > 8% increase → rising FALL_THRESHOLD = -0.08 # < -8% decrease → falling
if ratio > RISE_THRESHOLD: pattern = "rising" elif ratio < FALL_THRESHOLD: pattern = "falling" else: pattern = "flat"
return { "actual_pattern": pattern, "f0_start": round(f0_start, 1), "f0_end": round(f0_end, 1), "f0_change_ratio": round(ratio, 3), }
def analyze( audio_path: str, target_text: str, target_type: str = "sentence",) -> ComponentResult: """Phân tích ngữ điệu (rising/falling) dựa trên F0 contour."""
if target_type == "word": return ComponentResult( name="intonation", score=100, available=False, feedback="", warning="Intonation chỉ áp dụng cho câu.", )
if not _PARSELMOUTH_AVAILABLE: return ComponentResult( name="intonation", score=100, available=False, warning="praat-parselmouth chưa được cài.", feedback="Không thể phân tích ngữ điệu.", )
try: f0_frames = _extract_f0_peaks(audio_path) if not f0_frames: return ComponentResult( name="intonation", score=50, available=False, warning="Không trích xuất được F0.", feedback="Không đủ dữ liệu F0.", )
expected_pattern = _detect_expected_pattern(target_text) contour = _analyze_f0_contour(f0_frames) actual_pattern = contour["actual_pattern"]
# Scoring if actual_pattern == expected_pattern: score = 100 feedback = f"Ngữ điệu đúng: {expected_pattern}." elif actual_pattern == "flat": # Flat thay vì rising/falling → penalty vừa score = 60 feedback = ( f"Ngữ điệu phẳng (flat). Kỳ vọng '{expected_pattern}'. " "Hãy thay đổi pitch ở cuối câu." ) else: # Rising thay vì falling hoặc ngược lại → penalty nặng score = 30 feedback = ( f"Ngữ điệu ngược: phát âm '{actual_pattern}' " f"nhưng kỳ vọng '{expected_pattern}'. " "Kiểm tra xem câu là câu hỏi hay câu trần thuật." )
details = [{ "expected_pattern": expected_pattern, **contour, }]
return ComponentResult( name="intonation", score=score, details=details, feedback=feedback, )
except Exception as e: print(f"Intonation analysis error: {e}") return ComponentResult( name="intonation", score=50, available=False, warning=str(e), feedback="Lỗi phân tích ngữ điệu.", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230"""Component 4: Linking Sounds / Connected Speech (Nối âm) — Weight 15%Rule-based detection dựa trên IPA word boundaries.Chỉ áp dụng cho target_type="sentence" hoặc "phrase"."""
from . import ComponentResult
try: from src.pronunciation import tokenize_ipa, get_expected_ipaexcept ImportError: from pronunciation import tokenize_ipa, get_expected_ipa
# Phoneme sets cho rule matching_CONSONANTS = { "p", "b", "t", "d", "k", "ɡ", "g", "ʔ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "tʃ", "dʒ", "t͡ʃ", "d͡ʒ", "m", "n", "ŋ", "l", "r", "ɹ", "j", "w",}
_VOWELS = { "iː", "ɪ", "eɪ", "ɛ", "e", "æ", "ɑː", "ɑ", "ɒ", "ɔː", "ɔ", "oʊ", "ɔɪ", "ʊ", "uː", "aɪ", "aʊ", "ə", "ɜː", "ɜ", "ʌ", "ɪə", "eə", "ʊə", "i", "u", "a", "o",}
def _get_last_phoneme(word_ipa: str) -> str | None: """Lấy phoneme cuối cùng của từ (bỏ stress marks).""" tokens = [t for t in tokenize_ipa(word_ipa) if t not in ("ˈ", "ˌ")] return tokens[-1] if tokens else None
def _get_first_phoneme(word_ipa: str) -> str | None: """Lấy phoneme đầu tiên của từ (bỏ stress marks).""" tokens = [t for t in tokenize_ipa(word_ipa) if t not in ("ˈ", "ˌ")] return tokens[0] if tokens else None
def _detect_linking_opportunities(word_ipas: list[str]) -> list[dict]: """ Detect các cơ hội nối âm giữa từng cặp từ liền kề.
Returns: list[{ word_pair: (str, str), pair_index: int, last_phoneme: str, first_phoneme: str, linking_type: str, expected_behavior: str, }] """ opportunities = []
for i in range(len(word_ipas) - 1): last_p = _get_last_phoneme(word_ipas[i]) first_p = _get_first_phoneme(word_ipas[i + 1])
if not last_p or not first_p: continue
linking_type = None expected = ""
# Type 1: Consonant → Vowel (nối phụ âm sang nguyên âm) if last_p in _CONSONANTS and first_p in _VOWELS: linking_type = "consonant_vowel" expected = f"Nối /{last_p}/ sang /{first_p}/ — đọc liền, không ngắt."
# Type 2: Same consonant at boundary (gemination → single release) elif last_p in _CONSONANTS and first_p in _CONSONANTS and last_p == first_p: linking_type = "gemination" expected = f"Hai /{last_p}/ liền nhau — chỉ release 1 lần."
# Type 3: Vowel → Vowel (intrusive /j/, /w/, /r/) elif last_p in _VOWELS and first_p in _VOWELS: # Check for intrusive consonant # High front vowels (i, ɪ, eɪ, aɪ, ɔɪ) → intrusive /j/ # High back vowels (u, ʊ, oʊ, aʊ) → intrusive /w/ # Schwa-like (ə, ɜ, ɑ) → intrusive /r/ (non-rhotic) HIGH_FRONT = {"iː", "ɪ", "eɪ", "aɪ", "ɔɪ", "i"} HIGH_BACK = {"uː", "ʊ", "oʊ", "aʊ", "u"} SCHWA_LIKE = {"ə", "ɜː", "ɜ", "ɑː", "ɑ"}
if last_p in HIGH_FRONT: linking_type = "intrusive_j" expected = f"Thêm /j/ nhẹ giữa /{last_p}/ và /{first_p}/." elif last_p in HIGH_BACK: linking_type = "intrusive_w" expected = f"Thêm /w/ nhẹ giữa /{last_p}/ và /{first_p}/." elif last_p in SCHWA_LIKE: linking_type = "intrusive_r" expected = f"Thêm /r/ nhẹ giữa /{last_p}/ và /{first_p}/ (linking R)."
# Type 4: Stop consonant at end → check for elision # (t/d/k at end before consonant → may be unreleased) elif last_p in {"t", "d", "k"} and first_p in _CONSONANTS: linking_type = "elision" expected = f"/{last_p}/ cuối từ có thể unreleased hoặc bị nuốt trước /{first_p}/."
if linking_type: opportunities.append({ "pair_index": i, "word_pair": (word_ipas[i], word_ipas[i + 1]), "last_phoneme": last_p, "first_phoneme": first_p, "linking_type": linking_type, "expected_behavior": expected, })
return opportunities
def _check_linking_in_actual( actual_ipa: str, opportunities: list[dict],) -> tuple[int, int, list[dict]]: """ Kiểm tra actual IPA có thực hiện linking đúng không. Heuristic: nếu linking consonant+vowel thì expected IPA boundary (pause/gap) không nên xuất hiện trong actual.
Returns: (correct_count, total_count, results) """ actual_tokens = tokenize_ipa(actual_ipa) if not actual_tokens: return 0, len(opportunities), [ {**opp, "is_correct": False, "reason": "no_actual_ipa"} for opp in opportunities ]
# Build actual phoneme string để search actual_str = " ".join(actual_tokens) results = [] correct = 0 total = len(opportunities)
for opp in opportunities: ltype = opp["linking_type"] last_p = opp["last_phoneme"] first_p = opp["first_phoneme"]
# Heuristic check: tìm sequence last_p + first_p liền kề trong actual if ltype == "consonant_vowel": # Nên thấy last_p ngay trước first_p (không có gap) search = f"{last_p} {first_p}" found = search in actual_str results.append({**opp, "is_correct": found, "reason": "linked" if found else "gap_detected"}) if found: correct += 1
elif ltype == "gemination": # Chỉ 1 instance (merged) thay vì 2 # Đếm occurrences — nếu ≤ expected thì OK results.append({**opp, "is_correct": True, "reason": "gemination_assumed_ok"}) correct += 1
elif ltype in ("intrusive_j", "intrusive_w", "intrusive_r"): # Intrusive sound khó detect → lenient results.append({**opp, "is_correct": True, "reason": "intrusive_lenient"}) correct += 1
elif ltype == "elision": # Nếu consonant bị drop → OK (elision is natural) results.append({**opp, "is_correct": True, "reason": "elision_accepted"}) correct += 1
else: results.append({**opp, "is_correct": True, "reason": "unknown_type"}) correct += 1
return correct, total, results
def analyze( actual_ipa: str, expected_ipa: str, target_text: str, target_type: str = "sentence",) -> ComponentResult: """ Phân tích nối âm giữa các từ. Chỉ có nghĩa với target_type="sentence". """ if target_type == "word": return ComponentResult( name="linking", score=100, available=False, feedback="", warning="Linking chỉ áp dụng cho câu/cụm từ.", )
word_ipas = [w.strip() for w in expected_ipa.split() if w.strip()] if len(word_ipas) < 2: return ComponentResult( name="linking", score=100, feedback="Chỉ có 1 từ — không cần kiểm tra nối âm.", )
# Detect opportunities opportunities = _detect_linking_opportunities(word_ipas) if not opportunities: return ComponentResult( name="linking", score=100, feedback="Không phát hiện cơ hội nối âm giữa các từ.", )
# Check actual correct, total, details = _check_linking_in_actual(actual_ipa, opportunities)
score = int((correct / total) * 100) if total > 0 else 100
wrong = [d for d in details if not d.get("is_correct", True)] if not wrong: feedback = f"Nối âm tốt: {total} điểm nối âm đều được thực hiện." else: parts = [] for d in wrong[:3]: parts.append(d.get("expected_behavior", "")) feedback = "Cần cải thiện nối âm: " + " | ".join(parts)
return ComponentResult( name="linking", score=score, details=details, feedback=feedback, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""Pronunciation Scorer — Weighted aggregation of all 7 components.Trả về combined final score + component breakdown."""
from dataclasses import dataclass, fieldfrom typing import Optionalfrom . import ComponentResult
# Import all 7 component modulesfrom . import ( individual_sounds, word_stress, sentence_stress, linking, intonation, chunking, contracted_words,)
try: from src.pronunciation import ( grade_pronunciation_advanced, get_expected_ipa, )except ImportError: from pronunciation import ( grade_pronunciation_advanced, get_expected_ipa, )
# ============================================================# WEIGHTS — Phân bổ theo target_type# ============================================================
WEIGHTS_SENTENCE = { "individual_sounds": 0.30, "word_stress": 0.20, "sentence_stress": 0.15, "linking": 0.15, "intonation": 0.10, "chunking": 0.05, "contracted_words": 0.05,}
WEIGHTS_WORD = { "individual_sounds": 0.60, "word_stress": 0.35, "contracted_words": 0.05,}
WEIGHTS_PHRASE = { "individual_sounds": 0.35, "word_stress": 0.20, "linking": 0.25, "intonation": 0.10, "contracted_words": 0.10,}
def _get_weights(target_type: str) -> dict[str, float]: """Lấy bộ trọng số phù hợp với target_type.""" if target_type == "word": return WEIGHTS_WORD elif target_type == "phrase": return WEIGHTS_PHRASE else: # sentence, ipa return WEIGHTS_SENTENCE
@dataclassclass PronunciationScore: """Kết quả tổng hợp của toàn bộ 7-component assessment.""" overall_score: int # 0–100 weighted final score components: dict[str, ComponentResult] = field(default_factory=dict) component_scores: dict[str, Optional[int]] = field(default_factory=dict) weights_used: dict[str, float] = field(default_factory=dict) feedback_text: str = "" target_type: str = "word"
def run_full_assessment( audio_path: str, target_text: str, target_type: str = "word",) -> PronunciationScore: """ Chạy đủ 7 components và tính weighted final score.
Args: audio_path: Đường dẫn file audio (wav/mp3). target_text: Văn bản mục tiêu. target_type: "word" | "phrase" | "sentence" | "ipa"
Returns: PronunciationScore với overall_score, component breakdown, feedback. """ # 1. IPA extraction ipa_data = grade_pronunciation_advanced(audio_path, target_text) actual_ipa = ipa_data.get("actual_ipa", "N/A") expected_ipa = ipa_data.get("expected_ipa", "N/A")
# 2. Run all 7 components components: dict[str, ComponentResult] = {}
# C1: Individual Sounds (luôn chạy) components["individual_sounds"] = individual_sounds.analyze( actual_ipa=actual_ipa, expected_ipa=expected_ipa, )
# C2: Word Stress (luôn chạy) components["word_stress"] = word_stress.analyze( audio_path=audio_path, target_text=target_text, expected_ipa=expected_ipa, target_type=target_type, )
# C3: Sentence Stress (chỉ sentence) components["sentence_stress"] = sentence_stress.analyze( audio_path=audio_path, expected_ipa=expected_ipa, target_type=target_type, )
# C4: Linking (sentence/phrase) components["linking"] = linking.analyze( actual_ipa=actual_ipa, expected_ipa=expected_ipa, target_text=target_text, target_type=target_type, )
# C5: Intonation (sentence/phrase) components["intonation"] = intonation.analyze( audio_path=audio_path, target_text=target_text, target_type=target_type, )
# C6: Chunking (sentence) components["chunking"] = chunking.analyze( audio_path=audio_path, target_text=target_text, target_type=target_type, )
# C7: Contracted Words (luôn chạy) components["contracted_words"] = contracted_words.analyze( actual_ipa=actual_ipa, target_text=target_text, target_type=target_type, )
# 3. Weighted final score weights = _get_weights(target_type) weighted_sum = 0.0 total_weight = 0.0 component_scores: dict[str, Optional[int]] = {}
for name, w in weights.items(): comp = components.get(name) if comp and comp.available: weighted_sum += comp.score * w total_weight += w component_scores[name] = comp.score else: component_scores[name] = None
# Components không có trong weights → None for name in components: if name not in component_scores: component_scores[name] = components[name].score if components[name].available else None
if total_weight > 0: overall_score = int(round(weighted_sum / total_weight)) else: overall_score = 0
overall_score = max(0, min(100, overall_score))
# 4. Aggregate feedback feedback_sections = [] for name in [ "individual_sounds", "word_stress", "sentence_stress", "linking", "intonation", "chunking", "contracted_words", ]: comp = components.get(name) if comp and comp.available and comp.feedback: label = _COMPONENT_LABELS.get(name, name) score_str = f"[{comp.score}/100]" if comp.score < 90 else "✅" feedback_sections.append(f"**{label}** {score_str}: {comp.feedback}")
if not feedback_sections: feedback_text = "Tuyệt vời! Phát âm chính xác ở tất cả các thành phần." else: feedback_text = "\n".join(feedback_sections)
return PronunciationScore( overall_score=overall_score, components=components, component_scores=component_scores, weights_used=weights, feedback_text=feedback_text, target_type=target_type, )
_COMPONENT_LABELS = { "individual_sounds": "Âm vị", "word_stress": "Trọng âm từ", "sentence_stress": "Trọng âm câu", "linking": "Nối âm", "intonation": "Ngữ điệu", "chunking": "Chia đoạn", "contracted_words": "Từ rút gọn",}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""Component 3: Sentence Stress (Trọng âm câu) — Weight 15%Refactored từ pronunciation.py analyze_sentence_stress().Chỉ áp dụng cho target_type="sentence"."""
import numpy as npfrom . import ComponentResult
try: from src.pronunciation import ( tokenize_ipa, _extract_f0_peaks, _PARSELMOUTH_AVAILABLE, )except ImportError: from pronunciation import ( tokenize_ipa, _extract_f0_peaks, _PARSELMOUTH_AVAILABLE, )
def _get_expected_stress_positions(expected_ipa: str) -> list[int]: """Vị trí phoneme có stress mark (ˈ/ˌ) trong expected IPA.""" tokens = tokenize_ipa(expected_ipa) stressed: list[int] = [] phoneme_idx = 0 for tok in tokens: if tok in ("ˈ", "ˌ"): stressed.append(phoneme_idx) else: phoneme_idx += 1 return stressed
def analyze( audio_path: str, expected_ipa: str, target_type: str = "sentence",) -> ComponentResult: """ Phân tích trọng âm câu bằng F0 peak mapping. Chỉ có nghĩa với target_type="sentence". """ if target_type != "sentence": return ComponentResult( name="sentence_stress", score=100, available=False, warning="Chỉ áp dụng cho câu.", feedback="", )
if not _PARSELMOUTH_AVAILABLE: return ComponentResult( name="sentence_stress", score=100, available=False, warning="praat-parselmouth chưa được cài.", feedback="Không thể phân tích trọng âm câu.", )
try: f0_frames = _extract_f0_peaks(audio_path) if not f0_frames: return ComponentResult( name="sentence_stress", score=50, available=False, warning="Không trích xuất được F0.", feedback="Không đủ dữ liệu F0 để phân tích trọng âm câu.", )
# Voiced frames voiced = [(i, v) for i, v in enumerate(f0_frames) if v > 0] if not voiced: return ComponentResult( name="sentence_stress", score=50, warning="Không phát hiện voiced segments.", feedback="Không đủ voiced segments.", )
# Syllable-like groups (voiced segments separated by gaps ≥ 60ms) GAP_THRESHOLD = 3 # frames (~60ms) groups: list[list[tuple[int, float]]] = [] current: list[tuple[int, float]] = [] prev_idx = -99
for idx, val in voiced: if current and idx - prev_idx > GAP_THRESHOLD: groups.append(current) current = [] current.append((idx, val)) prev_idx = idx if current: groups.append(current)
if not groups: return ComponentResult( name="sentence_stress", score=50, feedback="Không đủ voiced segments.", )
# F0 mean per group syl_f0 = [float(np.mean([v for _, v in g])) for g in groups] f0_max, f0_min = max(syl_f0), min(syl_f0) f0_range = f0_max - f0_min if f0_max > f0_min else 1.0 f0_norm = [(v - f0_min) / f0_range for v in syl_f0]
# Expected stress positions expected_stress_idx = _get_expected_stress_positions(expected_ipa) n_syllables = len(groups)
if not expected_stress_idx: return ComponentResult( name="sentence_stress", score=100, feedback="Không có stress marks trong expected IPA.", )
n_expected_phonemes = max(expected_stress_idx) + 1 details = [] matched = 0
for pos in expected_stress_idx: ratio = pos / max(n_expected_phonemes - 1, 1) syl_idx = min(int(ratio * n_syllables), n_syllables - 1) f0_at = f0_norm[syl_idx]
THRESHOLD = 0.4 is_high = f0_at >= THRESHOLD neighbors = [ f0_norm[max(0, syl_idx - 1)], f0_norm[min(n_syllables - 1, syl_idx + 1)], ] is_peak = f0_at >= max(neighbors) * 0.85
correct = is_high or is_peak if correct: matched += 1
details.append({ "expected_phoneme_idx": pos, "syllable_group_idx": syl_idx, "f0_normalized": round(f0_at, 3), "is_correctly_stressed": correct, })
# Rhythm check: variance of intervals between stress peaks # Lower variance → better rhythm (isochrony) stress_frame_positions = [] for d in details: g_idx = d["syllable_group_idx"] if g_idx < len(groups): avg_frame = np.mean([idx for idx, _ in groups[g_idx]]) stress_frame_positions.append(avg_frame)
rhythm_penalty = 0 if len(stress_frame_positions) >= 3: intervals = np.diff(stress_frame_positions) cv = np.std(intervals) / max(np.mean(intervals), 1) # CV > 0.5 = poor rhythm → penalty if cv > 0.5: rhythm_penalty = min(15, int(cv * 20))
total = len(expected_stress_idx) accuracy = matched / total if total > 0 else 1.0 score = max(0, int(50 + accuracy * 50) - rhythm_penalty)
wrong = [d for d in details if not d["is_correctly_stressed"]] if not wrong and rhythm_penalty == 0: feedback = "Trọng âm câu tốt, nhịp điệu đều." elif wrong: feedback = ( f"Phát hiện {len(wrong)}/{total} vị trí trọng âm câu chưa đúng. " "Hãy nhấn mạnh hơn vào từ quan trọng." ) else: feedback = "Trọng âm câu đúng nhưng nhịp điệu chưa đều."
return ComponentResult( name="sentence_stress", score=score, details=details, feedback=feedback, )
except Exception as e: print(f"Sentence stress analysis error: {e}") return ComponentResult( name="sentence_stress", score=50, available=False, warning=str(e), feedback="Lỗi phân tích trọng âm câu.", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364"""Component 2: Word Stress (Trọng âm từ) — Weight 20%Dùng Parselmouth F0 per-syllable + eSpeak stress positions.Librosa energy-based word boundary detection."""
import numpy as npfrom typing import Optionalfrom . import ComponentResult
try: from src.pronunciation import ( tokenize_ipa, get_expected_ipa, )except ImportError: from pronunciation import ( tokenize_ipa, get_expected_ipa, )
# Lazy import heavy deps_parselmouth = None_librosa = None
def _get_parselmouth(): global _parselmouth if _parselmouth is None: try: import parselmouth _parselmouth = parselmouth except ImportError: pass return _parselmouth
def _get_librosa(): global _librosa if _librosa is None: try: import librosa _librosa = librosa except ImportError: pass return _librosa
def _split_ipa_into_words(ipa_string: str) -> list[str]: """Tách IPA string thành list IPA cho từng từ (split bằng space).""" if not ipa_string or ipa_string in ("N/A", "Error"): return [] return [w.strip() for w in ipa_string.split() if w.strip()]
def _count_syllables_ipa(word_ipa: str) -> int: """Đếm syllable trong 1 từ IPA bằng cách đếm vowel nuclei.""" tokens = tokenize_ipa(word_ipa) VOWELS = { "iː", "ɪ", "eɪ", "ɛ", "e", "æ", "ɑː", "ɑ", "ɒ", "ɔː", "ɔ", "oʊ", "ɔɪ", "ʊ", "uː", "aɪ", "aʊ", "ə", "ɜː", "ɜ", "ʌ", "ɪə", "eə", "ʊə", "i", "u", "a", "o", } count = sum(1 for t in tokens if t in VOWELS) return max(count, 1)
def _get_stressed_syllable_index(word_ipa: str) -> Optional[int]: """ Trả về index (0-based) của syllable có primary stress (ˈ). None nếu không có stress mark. """ tokens = tokenize_ipa(word_ipa) VOWELS = { "iː", "ɪ", "eɪ", "ɛ", "e", "æ", "ɑː", "ɑ", "ɒ", "ɔː", "ɔ", "oʊ", "ɔɪ", "ʊ", "uː", "aɪ", "aʊ", "ə", "ɜː", "ɜ", "ʌ", "ɪə", "eə", "ʊə", "i", "u", "a", "o", } syllable_idx = -1 stress_at_next_vowel = False for tok in tokens: if tok == "ˈ": stress_at_next_vowel = True elif tok in VOWELS: syllable_idx += 1 if stress_at_next_vowel: return syllable_idx stress_at_next_vowel = False elif tok == "ˌ": pass # Secondary stress — skip cho giờ return None
def _detect_word_boundaries(audio_path: str, n_words: int) -> list[tuple[float, float]]: """ Detect word boundaries từ audio dùng librosa energy/onset. Trả về list (start_sec, end_sec) cho mỗi word. """ librosa = _get_librosa() if librosa is None: return []
try: y, sr = librosa.load(audio_path, sr=16000) duration = librosa.get_duration(y=y, sr=sr)
if n_words <= 1: return [(0.0, duration)]
# RMS energy envelope frame_length = 2048 hop_length = 512 rms = librosa.feature.rms(y=y, frame_length=frame_length, hop_length=hop_length)[0] times = librosa.frames_to_time( np.arange(len(rms)), sr=sr, hop_length=hop_length )
# Onset detection — tìm điểm bắt đầu năng lượng tăng đột biến onset_frames = librosa.onset.onset_detect( y=y, sr=sr, hop_length=hop_length, backtrack=True, units="frames", ) onset_times = librosa.frames_to_time(onset_frames, sr=sr, hop_length=hop_length)
# Nếu số onset < n_words, fallback proportional if len(onset_times) < n_words - 1: boundaries = [] segment = duration / n_words for i in range(n_words): boundaries.append((segment * i, segment * (i + 1))) return boundaries
# Chọn top (n_words - 1) onset mạnh nhất làm word boundaries # Ưu tiên onset có khoảng cách đều if len(onset_times) >= n_words - 1: # Lấy n_words-1 onset phân bố đều nhất target_positions = [duration * (i + 1) / n_words for i in range(n_words - 1)] selected = [] used = set() for target in target_positions: diffs = [(abs(ot - target), j) for j, ot in enumerate(onset_times) if j not in used] if diffs: _, best_idx = min(diffs) selected.append(onset_times[best_idx]) used.add(best_idx) selected.sort()
boundaries = [] prev = 0.0 for s in selected: boundaries.append((prev, s)) prev = s boundaries.append((prev, duration)) return boundaries
return [(0.0, duration)]
except Exception as e: print(f"Word boundary detection error: {e}") # Fallback: proportional split try: y, sr = librosa.load(audio_path, sr=16000) duration = librosa.get_duration(y=y, sr=sr) seg = duration / n_words return [(seg * i, seg * (i + 1)) for i in range(n_words)] except Exception: return []
def _get_f0_in_range(audio_path: str, start_sec: float, end_sec: float) -> list[float]: """Trích xuất F0 frames trong khoảng [start, end] giây.""" pm = _get_parselmouth() if pm is None: return [] try: from parselmouth.praat import call as praat_call sound = pm.Sound(audio_path) # Extract đoạn cần thiết segment = praat_call(sound, "Extract part", start_sec, end_sec, "rectangular", 1.0, "no") pitch = praat_call(segment, "To Pitch", 0.0, 75.0, 600.0) n_frames = int(praat_call(pitch, "Get number of frames")) f0s = [] for i in range(1, n_frames + 1): v = praat_call(pitch, "Get value in frame", i, "Hertz") f0s.append(float(v) if v == v else 0.0) return f0s except Exception as e: print(f"F0 extraction error: {e}") return []
def analyze( audio_path: str, target_text: str, expected_ipa: str, target_type: str = "word",) -> ComponentResult: """ Phân tích trọng âm từ. - Từ đơn: kiểm tra primary stress syllable có F0 peak - Câu: kiểm tra từng từ trong câu """ pm = _get_parselmouth() if pm is None: return ComponentResult( name="word_stress", score=100, available=False, warning="praat-parselmouth chưa được cài.", feedback="Không thể phân tích trọng âm từ (thiếu Parselmouth).", )
words = target_text.strip().split() word_ipas = _split_ipa_into_words(expected_ipa)
# Nếu chỉ 1 từ và ≤ 1 syllable → auto pass if len(words) <= 1: if word_ipas: n_syl = _count_syllables_ipa(word_ipas[0]) if n_syl <= 1: return ComponentResult( name="word_stress", score=100, feedback="Từ đơn 1 âm tiết — không cần kiểm tra trọng âm.", )
# Detect word boundaries word_bounds = _detect_word_boundaries(audio_path, len(words)) if not word_bounds: return ComponentResult( name="word_stress", score=75, available=False, warning="Không detect được word boundaries từ audio.", feedback="Không thể chia ranh giới từ trong audio.", )
# Phân tích từng word details = [] correct_count = 0 total_checked = 0
for i, word in enumerate(words): if i >= len(word_ipas) or i >= len(word_bounds): break
w_ipa = word_ipas[i] n_syl = _count_syllables_ipa(w_ipa)
if n_syl <= 1: # 1 syllable → auto correct (không có stress distinction) details.append({ "word": word, "word_ipa": w_ipa, "syllable_count": n_syl, "expected_stress_syllable": None, "is_correct": True, "reason": "monosyllabic", }) correct_count += 1 total_checked += 1 continue
expected_stress_syl = _get_stressed_syllable_index(w_ipa) if expected_stress_syl is None: # Không có stress mark trong IPA → skip details.append({ "word": word, "word_ipa": w_ipa, "syllable_count": n_syl, "expected_stress_syllable": None, "is_correct": True, "reason": "no_stress_mark", }) correct_count += 1 total_checked += 1 continue
# Lấy F0 trong word boundary start, end = word_bounds[i] f0_frames = _get_f0_in_range(audio_path, start, end)
if not f0_frames or all(v == 0 for v in f0_frames): details.append({ "word": word, "word_ipa": w_ipa, "syllable_count": n_syl, "expected_stress_syllable": expected_stress_syl, "is_correct": True, "reason": "no_voiced_data", }) correct_count += 1 total_checked += 1 continue
# Chia F0 frames thành n_syl syllable segments (proportional) voiced = [v for v in f0_frames if v > 0] if not voiced: details.append({ "word": word, "word_ipa": w_ipa, "syllable_count": n_syl, "expected_stress_syllable": expected_stress_syl, "is_correct": True, "reason": "no_voiced_data", }) correct_count += 1 total_checked += 1 continue
frames_per_syl = max(1, len(f0_frames) // n_syl) syl_f0_means = [] for s in range(n_syl): start_frame = s * frames_per_syl end_frame = start_frame + frames_per_syl if s < n_syl - 1 else len(f0_frames) chunk = f0_frames[start_frame:end_frame] voiced_chunk = [v for v in chunk if v > 0] syl_f0_means.append(np.mean(voiced_chunk) if voiced_chunk else 0.0)
# Syllable với F0 cao nhất = stressed syllable (actual) if syl_f0_means: actual_stress_syl = int(np.argmax(syl_f0_means)) is_correct = actual_stress_syl == expected_stress_syl
# Tolerant: nếu difference < 15% thì vẫn coi là đúng if not is_correct and max(syl_f0_means) > 0: expected_f0 = syl_f0_means[expected_stress_syl] max_f0 = max(syl_f0_means) if expected_f0 / max_f0 > 0.85: is_correct = True else: actual_stress_syl = None is_correct = True
if is_correct: correct_count += 1
total_checked += 1 details.append({ "word": word, "word_ipa": w_ipa, "syllable_count": n_syl, "expected_stress_syllable": expected_stress_syl, "actual_stress_syllable": actual_stress_syl, "syllable_f0_means": [round(v, 1) for v in syl_f0_means], "is_correct": is_correct, })
# Score if total_checked == 0: score = 100 else: score = int((correct_count / total_checked) * 100)
# Feedback wrong = [d for d in details if not d.get("is_correct", True)] if not wrong: feedback = "Trọng âm từ chính xác." else: parts = [] for d in wrong[:3]: w = d.get("word", "") exp = d.get("expected_stress_syllable", "?") parts.append(f"'{w}' — cần nhấn âm tiết {exp + 1}") feedback = "Sai trọng âm: " + "; ".join(parts) + "."
return ComponentResult( name="word_stress", score=score, details=details, feedback=feedback, )