Prosodia-Seq
Prosodia-Seq is a concise toolkit for converting English phoneme sequences into natural, context-aware Mandarin pinyin approximations. It combines a sequence-to-sequence model with a rule-based SmartResolver that adjusts outputs based on neighbouring phonemes and prosodic cues, and emits per-syllable confidence and approximation metadata suitable for analysis and visualization.
Primary use cases: building pronunciation guides, creating pronunciation-aware educational content, and preprocessing English speech text for language tools.
Example: Ok → ou1kei4
Getting Started — Using the Trained Pinyin Model (Standalone)
Minimal Python example (load & predict)
Copy this snippet into your project (make sure you install project dependencies and put the checkpoint dir next to it). It uses the built-in inference wrapper PinyinPredictor.
import sys
sys.path.insert(0, '.')
from src.ml.inference import PinyinPredictor
checkpoint_dir = 'checkpoints_small'
predictor = PinyinPredictor.from_checkpoint(checkpoint_dir)
words = ['ok', 'hello', 'want', 'sing', 'long']
for w in words:
result = predictor.predict_word(w)
print(f"{w:10} -> {' '.join(result.predicted_pinyin)}")
Notes:
PinyinPredictor.from_checkpoint()will loadmodel_state_dictplus the tokenizers from the checkpoint directory.- The returned object includes
predict_word()(single word) andpredict_batch()helpers.
1. Core Philosophy: “Context Over Strictness”
Traditional transliteration uses simple 1-to-1 phoneme mapping:
Pinyin = lookup(Phoneme)
This fails because it ignores how sounds blend in natural speech. The SmartResolver uses:
Pinyin = Resolve(CurrentPhoneme, PreviousPhoneme, NextPhoneme)
2. Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ CMU Dict / │────▶│ SmartResolver │────▶│ Pinyin Output │
│ Phoneme List │ │ (Context-Aware) │ │ with Metadata │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
▼
┌──────────────────┐
│ ResolvedPhoneme │
│ - pinyin │
│ - is_approx │
│ - note │
│ - confidence │
└──────────────────┘
Key Files
| File | Purpose |
|---|---|
src/smart_resolver.py |
Context-aware resolution engine |
src/pinyin_converter.py |
Integration layer, uses SmartResolver |
src/mappings.py |
Base phoneme mappings (fallback) |
test_pronunciation.py |
Interactive testing CLI |
3. The “TH” Strategy
The CMU Dictionary distinguishes between two TH sounds:
- TH (Theta, θ): Voiceless - “think”, “math”, “with”
- DH (Eth, ð): Voiced - “the”, “this”, “father”
3.1 Handling DH (Voiced)
Base approximation: Z (buzzing sound like “ze”)
| Context (Next Sound) | Example | Pinyin | Rationale |
|---|---|---|---|
| Neutral / Schwa | the (DH AH) | ze |
Captures the buzz |
| Front Vowel (IY, IH) | this (DH IH S) | zei |
Flows into “i” naturally |
| Round Vowel (OW, UW) | those (DH OW Z) | zou |
Matches mouth shape |
| End of Word | breathe | zi |
Soft landing |
3.2 Handling TH (Voiceless)
Base approximation: S (sibilant) or X (before high vowels)
| Context (Next Sound) | Example | Pinyin | Rationale |
|---|---|---|---|
| High Front (IY) | theme | xi |
Softer than “si”, matches pitch |
| Standard (IH) | think | sin |
Standard dental approximation |
| Back Vowel (UH, AH) | thumb | san |
Open mouth mimicry |
| End of Word | math | si |
Trailing “hiss” |
4. Other Problematic Sounds
4.1 The “V” Problem
Mandarin has no “V” sound. Native speakers substitute with “W” or “F”.
| Position | Example | Pinyin | Rationale |
|---|---|---|---|
| Initial (before vowel) | very | wei |
Flows naturally |
| Final / before consonant | have | fu |
Harder sound |
4.2 Consonant Clusters
English allows consonant clusters (ST-R-EE-T). Mandarin requires CV structure.
Strategy: Insert “ghost vowels” based on the consonant type.
| Cluster | Example | Resolution | Output |
|---|---|---|---|
| TR | street | Blend to cui |
si cui yi te |
| DR | drive | Blend to zhui |
zhui ai wu |
| BL | blue | Separate | bo lu |
4.3 R-Colored Vowels (ER)
Good news: Mandarin “er” (儿) is a very close match!
| Phoneme | Example | Pinyin | Confidence |
|---|---|---|---|
| ER | bird, water | er |
95% |
5. Implementation Reference
SmartResolver Class
class SmartResolver:
def resolve(self, phoneme_list: List[str], index: int) -> ResolvedPhoneme:
"""
Main entry point. Looks at phoneme_list[index] and its neighbors.
Returns ResolvedPhoneme with pinyin, confidence, and notes.
"""
pass
# Specific handlers
def _resolve_dh(self, prev, next) -> ResolvedPhoneme: ...
def _resolve_th(self, prev, next) -> ResolvedPhoneme: ...
def _resolve_v(self, prev, next) -> ResolvedPhoneme: ...
def _resolve_r(self, prev, next) -> ResolvedPhoneme: ...
def _resolve_cluster(self, base, prev, next) -> ResolvedPhoneme: ...
ResolvedPhoneme Structure
@dataclass
class ResolvedPhoneme:
pinyin: str # Resolved syllable without tone
is_approximation: bool # True if heuristic guess
note: Optional[str] # Pronunciation tip
confidence: float # 0.0-1.0
Output JSON Schema (Enhanced)
{
"word": "the",
"p": ["DH", "AH0"],
"z": ["ze5", "e5"],
"f": ["."],
"segments": [
{
"text": "ze5",
"tone": "5",
"is_approx": true,
"confidence": 0.7,
"note": "舌头放在牙齿之间,声带振动"
},
{
"text": "e5",
"tone": "5",
"is_approx": false,
"confidence": 1.0
}
]
}
6. Confidence Levels
| Level | Range | Meaning |
|---|---|---|
| High | 0.9-1.0 | Direct mapping exists in Mandarin |
| Medium | 0.7-0.89 | Good approximation with context |
| Low | 0.5-0.69 | Heuristic guess, marked as approx |
| Very Low | <0.5 | Unknown sound, fallback used |
7. Frontend Styling Hints
The is_approx flag enables differentiated styling:
| Flag | Suggested Style |
|---|---|
is_approx: false |
Normal text (black) |
is_approx: true |
Gray text or subtle underline |
Has note |
Show tooltip on hover/tap |
8. Test Suite
Validate the SmartResolver with these edge cases:
| Word | Phonemes | Expected Output | Test Focus |
|---|---|---|---|
| the | DH AH0 | ze e | DH + schwa |
| think | TH IH1 NG K | sin yi ng ke | TH + IH |
| theme | TH IY1 M | xi yi mo | TH + high vowel |
| very | V EH1 R IY0 | wei ei rui yi | V initial |
| street | S T R IY1 T | si cui yi te | TR cluster |
| father | F AA1 DH ER0 | fu a ze er | DH + ER |
9. Extension Points
Adding New Phoneme Handlers
- Add method
_resolve_XX(self, prev, next)toSmartResolver - Add routing in
resolve()method - Add to
self.notesdictionary if needed - Add test cases to
test_pronunciation.py
Adjusting Mappings
- Modify
self.base_consonantsorself.base_vowelsinSmartResolver.__init__() - Update
PHONEME_TO_PINYINinmappings.pyfor legacy fallback - Run test suite to verify changes
10. Known Limitations
-
Homophone ambiguity: Same pinyin can map to multiple Chinese characters. Frontend should not show characters.
-
Dialect variation: Some Mandarin dialects have different sounds. We target Standard Mandarin (普通话).
-
Connected speech: Word boundaries change pronunciation. Current system handles words in isolation.
-
Tone sandhi: Mandarin tone rules (e.g., 3-3 → 2-3) are not applied. Tones indicate English stress, not Mandarin meaning.