ในยุคที่การสื่อสารข้ามภาษาเป็นสิ่งจำเป็นอย่างยิ่ง การสร้าง Translation Bot ที่สามารถแปลเสียงพูดแบบเรียลไทม์จึงกลายเป็นทักษะที่ Developer หลายคนต้องการ ในบทความนี้เราจะพาคุณสร้าง Translation Bot ตั้งแต่เริ่มต้น โดยใช้ Whisper API สำหรับการถอดเสียง และ GPT-4o จาก HolySheep AI สำหรับการแปลภาษาอย่างมีประสิทธิภาพ
เปรียบเทียบบริการ AI API ยอดนิยม
| บริการ | อัตรา (ต่อ 1M Tokens) | ความหน่วง (Latency) | วิธีการชำระเงิน | ประหยัดเมื่อเทียบกับ Official |
|---|---|---|---|---|
| HolySheep AI | ¥1 = $1 (GPT-4.1 $8) | <50ms | WeChat, Alipay, บัตร | ประหยัด 85%+ |
| OpenAI Official | $15 - $60 | 100-300ms | บัตรเครดิตเท่านั้น | ราคาอ้างอิง |
| Anthropic Official | $15 - $75 | 150-400ms | บัตรเครดิตเท่านั้น | ราคาสูงกว่า |
| บริการ Relay อื่นๆ | $10 - $40 | 80-200ms | หลากหลาย | ประหยัด 30-50% |
จากการเปรียบเทียบจะเห็นได้ว่า HolySheep AI ให้ความคุ้มค่าสูงสุด ด้วยอัตราแลกเปลี่ยน ¥1 = $1 ทำให้คุณประหยัดได้มากกว่า 85% เมื่อเทียบกับการใช้ API อย่างเป็นทางการ พร้อมความหน่วงต่ำกว่า 50ms ที่เหมาะสำหรับงานเรียลไทม์
ขั้นตอนที่ 1: ติดตั้งและตั้งค่าสภาพแวดล้อม
ก่อนเริ่มสร้าง Translation Bot เราต้องติดตั้ง dependencies ที่จำเป็นก่อน:
# ติดตั้ง Python packages ที่จำเป็น
pip install openai python-dotenv pyaudio websockets
หรือใช้ requirements.txt
openai>=1.0.0
python-dotenv>=1.0.0
pyaudio>=0.2.14
websockets>=12.0
หมายเหตุ: หากติดตั้ง PyAudio ไม่ได้บน Windows ให้ใช้คำสั่ง pip install pipwin && pipwin install pyaudio แทน
ขั้นตอนที่ 2: สร้าง Translation Bot ด้วย Whisper และ GPT-4o
มาสร้าง Translation Bot ที่ทำงานแบบเรียลไทม์กัน โดยเราจะใช้ HolySheep AI เป็น API endpoint:
import os
import json
import base64
import asyncio
import numpy as np
from openai import OpenAI
from dotenv import load_dotenv
import pyaudio
โหลด Environment Variables
load_dotenv()
ตั้งค่า HolySheep AI API
สำคัญ: base_url ต้องเป็น https://api.holysheep.ai/v1 เท่านั้น
client = OpenAI(
api_key=os.getenv("YOUR_HOLYSHEEP_API_KEY"),
base_url="https://api.holysheep.ai/v1"
)
กำหนดค่าคงที่สำหรับ Audio
SAMPLE_RATE = 16000
CHUNK_SIZE = 1024
TARGET_LANGUAGE = "Thai"
class RealtimeTranslator:
def __init__(self):
self.audio = pyaudio.PyAudio()
self.is_recording = False
self.audio_buffer = []
def record_audio(self):
"""เริ่มบันทึกเสียงจากไมค์"""
stream = self.audio.open(
format=pyaudio.paInt16,
channels=1,
rate=SAMPLE_RATE,
input=True,
frames_per_buffer=CHUNK_SIZE
)
self.is_recording = True
print("🎤 เริ่มบันทึกเสียง... (กด Ctrl+C เพื่อหยุด)")
while self.is_recording:
data = stream.read(CHUNK_SIZE)
self.audio_buffer.append(data)
def transcribe_audio(self, audio_data):
"""ถอดเสียงเป็นข้อความด้วย Whisper"""
# แปลง audio bytes เป็น base64
audio_base64 = base64.b64encode(audio_data).decode()
response = client.audio.transcriptions.create(
model="whisper-1",
file=("audio.wav", audio_data),
response_format="text"
)
return response.text
def translate_text(self, text, source_lang="auto", target_lang=TARGET_LANGUAGE):
"""แปลข้อความด้วย GPT-4o"""
if not text.strip():
return ""
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"""You are a professional translator.
Translate the following text to {target_lang}.
Only return the translated text, nothing else.
Preserve the tone and meaning of the original."""
},
{
"role": "user",
"content": text
}
],
temperature=0.3,
max_tokens=2000
)
return response.choices[0].message.content
def process_audio_chunk(self, chunk):
"""ประมวลผล chunk ของเสียง"""
try:
# ถอดเสียง
text = self.transcribe_audio(chunk)
if not text:
return None
# แปลข้อความ
translated = self.translate_text(text)
return {
"original": text,
"translated": translated,
"timestamp": asyncio.get_event_loop().time()
}
except Exception as e:
print(f"❌ เกิดข้อผิดพลาด: {e}")
return None
def stop(self):
"""หยุดการบันทึก"""
self.is_recording = False
self.audio.terminate()
async def main():
translator = RealtimeTranslator()
try:
# เริ่มบันทึกเสียงใน Thread แยก
import threading
record_thread = threading.Thread(
target=translator.record_audio
)
record_thread.start()
# รอให้มีข้อมูลเพียงพอ แล้วประมวลผล
while translator.is_recording:
if len(translator.audio_buffer) >= 10: # ทุก 10 chunks
# รวม audio chunks
audio_data = b''.join(translator.audio_buffer[-10:])
# ประมวลผล
result = translator.process_audio_chunk(audio_data)
if result:
print(f"\n📝 ต้นฉบับ: {result['original']}")
print(f"🌐 แปลเป็นไทย: {result['translated']}\n")
await asyncio.sleep(0.5)
except KeyboardInterrupt:
print("\n🛑 หยุดการทำงาน...")
finally:
translator.stop()
record_thread.join()
if __name__ == "__main__":
asyncio.run(main())
ขั้นตอนที่ 3: สร้าง WebSocket Server สำหรับ Production
สำหรับการใช้งานจริงใน Production เราควรสร้าง WebSocket Server ที่รองรับการเชื่อมต่อพร้อมกันหลายผู้ใช้:
import os
import json
import base64
import asyncio
import websockets
from openai import OpenAI
from collections import defaultdict
ตั้งค่า HolySheep AI API
client = OpenAI(
api_key=os.environ.get("YOUR_HOLYSHEEP_API_KEY"),
base_url="https://api.holysheep.ai/v1"
)
เก็บ session ของผู้ใช้แต่ละคน
active_sessions = defaultdict(dict)
async def translate_stream(audio_base64, target_lang="th"):
"""
แปลข้อความแบบ Streaming
ราคา: GPT-4o $8/MTok, Whisper $0.006/นาที
"""
try:
# ถอดเสียงด้วย Whisper API
audio_bytes = base64.b64decode(audio_base64)
# เรียก Whisper API ผ่าน HolySheep
transcript_response = client.audio.transcriptions.create(
model="whisper-1",
file=("audio.wav", audio_bytes),
response_format="verbose_json"
)
original_text = transcript_response.text
# แปลด้วย GPT-4o Streaming
stream = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"""You are a professional translator.
Translate to {target_lang} language.
Keep it natural and conversational."""
},
{
"role": "user",
"content": original_text
}
],
temperature=0.3,
max_tokens=1000,
stream=True
)
# รวบรวมผลลัพธ์ streaming
translated_chunks = []
for chunk in stream:
if chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
translated_chunks.append(content)
yield f"data: {json.dumps({'type': 'chunk', 'content': content})}\n\n"
# ส่งผลลัพธ์สุดท้าย
full_translation = ''.join(translated_chunks)
yield f"data: {json.dumps({'type': 'complete', 'original': original_text, 'translated': full_translation})}\n\n"
except Exception as e:
yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"
async def websocket_handler(websocket, path):
"""จัดการ WebSocket connection"""
client_id = id(websocket)
active_sessions[client_id] = {
'websocket': websocket,
'connected_at': asyncio.get_event_loop().time()
}
print(f"✅ ผู้ใช้ {client_id} เชื่อมต่อแล้ว")
try:
async for message in websocket:
data = json.loads(message)
if data['type'] == 'audio':
# ประมวลผลเสียงและส่งผลลัพธ์กลับ
target_lang = data.get('target_lang', 'th')
async for response in translate_stream(data['audio'], target_lang):
await websocket.send(response)
elif data['type'] == 'ping':
await websocket.send(json.dumps({'type': 'pong'}))
elif data['type'] == 'stop':
break
except websockets.exceptions.ConnectionClosed:
print(f"❌ ผู้ใช้ {client_id} ตัดการเชื่อมต่อ")
finally:
del active_sessions[client_id]
async def main():
# ราคาจริงจาก HolySheep AI (2026)
pricing = {
"gpt_4o": "$8/MTok",
"whisper": "$0.006/นาที",
"exchange_rate": "¥1 = $1 (ประหยัด 85%+)"
}
print("=" * 50)
print("🎙️ Realtime Translation Bot Server")
print("=" * 50)
print(f"📊 ราคา API: {pricing}")
print(f"🌐 Endpoint: ws://localhost:8000")
print(f"⚡ Latency: <50ms (HolySheep)")
print("=" * 50)
async with websockets.serve(websocket_handler, "0.0.0.0", 8000):
print("🚀 Server เริ่มทำงานแล้ว...")
await asyncio.Future() # Run forever
if __name__ == "__main__":
asyncio.run(main())
สร้าง Frontend Client ด้วย JavaScript
ส่วน Frontend สำหรับผู้ใช้งาน:
<!-- index.html -->
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🎙️ Realtime Translator</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Sarabun', sans-serif;
background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
color: white;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
background: rgba(255,255,255,0.1);
padding: 2rem;
border-radius: 20px;
backdrop-filter: blur(10px);
max-width: 600px;
width: 90%;
}
h1 { text-align: center; margin-bottom: 1.5rem; }
.btn {
width: 100%;
padding: 1rem;
border: none;
border-radius: 10px;
font-size: 1.2rem;
cursor: pointer;
margin: 0.5rem 0;
transition: all 0.3s;
}
.btn-start { background: #4CAF50; color: white; }
.btn-stop { background: #f44336; color: white; }
.btn:hover { transform: scale(1.02); }
.output {
margin-top: 1.5rem;
padding: 1rem;
background: rgba(0,0,0,0.3);
border-radius: 10px;
min-height: 150px;
}
.original, .translated {
padding: 0.5rem;
margin: 0.5rem 0;
border-radius: 8px;
}
.original { background: rgba(255,255,255,0.1); }
.translated { background