Download indextts/testipa.py from williampike/thai_indextts2: direct link, hf CLI and curl.
- Browser
- Download file 2.75 kB
-
https://huggingface.co/williampike/thai_indextts2/resolve/main/indextts/testipa.py
- Command line
-
hf download hf://williampike/thai_indextts2/indextts/testipa.py
-
curl -L -o testipa.py https://huggingface.co/williampike/thai_indextts2/resolve/main/indextts/testipa.py
2.75 kB
| import re | |
| from pythainlp.tokenize import word_tokenize | |
| from pythainlp.transliterate import transliterate | |
| class ThaiIPAPreprocessor: | |
| def __init__(self): | |
| # พจนานุกรมคำทับศัพท์ (แปลงเป็นไทยก่อน เพื่อให้ thaig2p อ่านถูก) | |
| self.en_th_dict = { | |
| "facebook": "เฟซบุ๊ก", "youtube": "ยูทูบ", "twitter": "ทวิตเตอร์", | |
| "ai": "เอไอ", "update": "อัปเดต", "app": "แอป", | |
| "chatgpt": "แชตจีพีที", "python": "ไพธอน" | |
| } | |
| def text_to_ipa(self, text): | |
| if not text: | |
| return "" | |
| for en, th in self.en_th_dict.items(): | |
| text = re.sub(r'(?i)\b' + en + r'\b', th, text) | |
| words = word_tokenize(text, engine="newmm") | |
| ipa_results = [] | |
| for w in words: | |
| if not re.match(r'^[ก-๙]+$', w): | |
| ipa_results.append(w) | |
| continue | |
| try: | |
| ipa = transliterate(w, engine="thaig2p") | |
| ipa = ipa.replace("-", "") | |
| ipa = " ".join(ipa.split()) | |
| ipa_results.append(ipa) | |
| except Exception as e: | |
| ipa_results.append(w) | |
| return " ".join(ipa_results) | |
| if __name__ == "__main__": | |
| g2p = ThaiIPAPreprocessor() | |
| problematic_texts = [ | |
| # 1. คำพ้องรูป (เขียนเหมือน อ่านต่าง) | |
| "เพลารถหักตอนเพลาเย็น", | |
| "ปลาปักเป้าลอยอยู่ใกล้ว่าวปักเป้า", | |
| # 2. ชื่อเฉพาะ / คำอ่านยาก | |
| "กฤตยชญ์เรียนที่มหาวิทยาลัยพระจอมเกล้าธนบุรี", | |
| "นายณัฏฐ์เป็นนายกรัฐมนตรี", | |
| # 3. ภาษาอังกฤษที่ไม่มีในดิกชันนารี (Out-of-vocabulary) | |
| "ฉันเขียนโค้ดด้วยภาษา HTML และ CSS", | |
| # 4. ตัวอักษรย่อ | |
| "ผอ. ร.ร. ไป กทม." | |
| ] | |
| print("="*50) | |
| print("🔥 PROBLEMATIC TEXT TESTER") | |
| print("="*50) | |
| for sentence in problematic_texts: | |
| ipa_output = g2p.text_to_ipa(sentence) | |
| print(f"📝 Text : {sentence}") | |
| print(f"🗣️ IPA : {ipa_output}") | |
| print("-" * 50) |