translet / server.py
bllndebrahim's picture
Clean history (free space)
ae033d7
Raw History Blame Contribute Delete
72.7 kB
import asyncio import base64 import edge_tts import hashlib import io import json import numpy as np import os import re import socket import struct import sys import urllib.parse import urllib.request import wave from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from scipy import signal import requests FAST_HTTP_SESSION = requests.Session() adapter = requests.adapters.HTTPAdapter(pool_connections=20, pool_maxsize=20) FAST_HTTP_SESSION.mount('https://', adapter) FAST_HTTP_SESSION.mount('http://', adapter) sys.stdout.reconfigure(encoding='utf-8') CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "audio_cache") os.makedirs(CACHE_DIR, exist_ok=True) GEMINI_KEY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".gemini_key") MAX_REQUEST_BYTES = 25 * 1024 * 1024 # 25 MB is plenty for a voice clip def get_gemini_key(user_key=""): """Gemini key: from the request, else the GEMINI_API_KEY env var, else the private .gemini_key file. The key is never written in the code, so it is never sent to browsers or uploaded anywhere.""" if user_key and user_key.strip(): return user_key.strip() env_key = os.environ.get("GEMINI_API_KEY", "").strip() if env_key: return env_key try: with open(GEMINI_KEY_FILE, "r", encoding="utf-8") as f: return f.read().strip() except Exception: return "" def sanitize_kurdish_sorani(text): """Ensures authentic Sorani Kurdish greeting 'سڵاو' is always preserved and never converted to 'سلاڤ', and converts unnatural literal possessives into native Sorani Kurdish.""" if not text: return text # Sorani Kurdish Greeting normalization text = re.sub(r'(?<!\w)سلاڤ(?!\w)', 'سڵاو', text) text = re.sub(r'(?<!\w)سلاڤان(?!\w)', 'سڵاوان', text) text = re.sub(r'(?<!\w)سلاو(?!\w)', 'سڵاو', text) text = re.sub(r'\b[sS]ilav\b', 'سڵاو', text) text = re.sub(r'\b[sS]lav\b', 'سڵاو', text) text = re.sub(r'\b[sS]law\b', 'سڵاو', text) # Convert unnatural literal possessives (فارسی/عەرەبی دەقاودەق) to authentic Sorani Kurdish text = re.sub(r'(?<!\w)برای\s+من(?!\w)', 'برام', text) text = re.sub(r'(?<!\w)براکەی\s+من(?!\w)', 'براکەم', text) text = re.sub(r'(?<!\w)خوشکی\s+من(?!\w)', 'خوشکم', text) text = re.sub(r'(?<!\w)خوشکەکەی\s+من(?!\w)', 'خوشکەکەم', text) text = re.sub(r'(?<!\w)هاو[ڕر]ێی\s+من(?!\w)', 'هاوڕێکەم', text) text = re.sub(r'(?<!\w)هاو[ڕر]ێکەی\s+من(?!\w)', 'هاوڕێکەم', text) text = re.sub(r'(?<!\w)دایکی\s+من(?!\w)', 'دایکم', text) text = re.sub(r'(?<!\w)باوکی\s+من(?!\w)', 'باوکم', text) text = re.sub(r'(?<!\w)ماڵی\s+من(?!\w)', 'ماڵم', text) text = re.sub(r'(?<!\w)ماڵەکەی\s+من(?!\w)', 'ماڵەکەم', text) text = re.sub(r'(?<!\w)ناوی\s+من(?!\w)', 'ناوم', text) text = re.sub(r'(?<!\w)کاری\s+من(?!\w)', 'کارم', text) text = re.sub(r'(?<!\w)کتێبی\s+من(?!\w)', 'کتێبەکەم', text) text = re.sub(r'(?<!\w)تۆ\s+چۆنیت(?!\w)', 'چۆنیت', text) try: text = normalize_kurdish_numbers(text) except Exception: pass return text def normalize_kurdish_for_neural(text, dialect="sorani"): """ Normalizes Kurdish text for the neural speech engine so every phoneme and dialect is articulated with true human naturalness and native vocabulary. """ if not text: return "" s = text.strip() # Normalize Kurdish ligatures & punctuation s = s.replace("،", " , ").replace("؟", " ? ").replace("؛", " ; ") s = s.replace("«", '"').replace("»", '"').replace("ـ", "") # For Badini dialect, adapt typical Badini vocabulary and pronunciation if dialect == "badini": badini_map = [ (r'\bچۆنی\b', 'چەوانی'), (r'\bچۆنن\b', 'چەوانن'), (r'\bبەخێربێیت\b', 'ب خێر هاتی'), (r'\bبەخێربێن\b', 'ب خێر هاتن'), (r'\bتکایە\b', 'هیڤیدارم'), (r'\bئەمڕۆ\b', 'ئەڤرۆ'), (r'\bئێستا\b', 'نوکە'), (r'\bبەیانی باش\b', 'سپێدە باش'), (r'\bشەو باش\b', 'شەڤ باش'), (r'\bڕۆژ باش\b', 'ڕۆژ باش'), (r'\bزۆر\b', 'گەلەک'), (r'\bسوپاس\b', 'دەستخۆش'), (r'\bهەموو\b', 'هەمی'), (r'\bباشی\b', 'ساخی'), (r'\bباشیت\b', 'باشی'), (r'\bخۆشەویست\b', 'خۆشتڤی'), (r'\bدەچم\b', 'دچم'), (r'\bدێم\b', 'دهێم'), (r'\bخواردن\b', 'خوارن'), (r'\bخەوتن\b', 'نڤستن'), (r'\bدەزانم\b', 'دزانم'), (r'\bنازانم\b', 'نزانم'), (r'\bدەستپێک\b', 'دەسپێک'), ] for pat, rep in badini_map: s = re.sub(pat, rep, s) elif dialect == "kurmanji": kurmanji_map = [ (r'\bچۆنی\b', 'چاوانی'), (r'\bچۆنن\b', 'چەوانن'), (r'\bبەخێربێیت\b', 'ب خێر هاتی'), (r'\bبەخێربێن\b', 'ب خێر هاتن'), (r'\bتکایە\b', 'تکایە'), (r'\bئەمڕۆ\b', 'ئیرۆ'), (r'\bئێستا\b', 'نەها'), (r'\bبەیانی باش\b', 'سپێدە باش'), (r'\bشەو باش\b', 'شەڤ باش'), (r'\bزۆر\b', 'گەلەک'), (r'\bسوپاس\b', 'سپاس'), (r'\bهەموو\b', 'هەمی'), (r'\bدەچم\b', 'دچم'), (r'\bخواردن\b', 'خوارن'), (r'\bدەستپێک\b', 'دەسپێک'), ] for pat, rep in kurmanji_map: s = re.sub(pat, rep, s) # 1. Normalization of irregular Kurdish words with silent "w" (واوی نەبزوێن لە وشە شازەکان): shaz_map = [ (r'\bدەخوێن(\w*)\b', r'دەخێن\1'), (r'\bدەخوێندر(\w*)\b', r'دەخێندر\1'), (r'\bبخوێن(\w*)\b', r'بخێن\1'), (r'\bخوێند(\w*)\b', r'خێند\1'), (r'\bخوێنەر(\w*)\b', r'خێنەر\1'), (r'\bخوێن(مژ|اوی|ەکەم|ەکە)\b', r'خێن\1'), (r'\bخوێ(دان|ەکە|ەم)\b', r'خێ\1'), (r'\bخوشک(\w*)\b', r'خیشک\1'), ] for pat, rep in shaz_map: s = re.sub(pat, rep, s) return s async def synthesize_speech(text, voice, rate="+0%", pitch="+0Hz"): cache_key = hashlib.md5(f"{text}|{voice}|{rate}|{pitch}".encode('utf-8')).hexdigest() cache_file = os.path.join(CACHE_DIR, f"{cache_key}.mp3") if os.path.exists(cache_file) and os.path.getsize(cache_file) > 500: with open(cache_file, "rb") as f: return f.read() comm = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch) audio_data = b"" async for chunk in comm.stream(): if chunk["type"] == "audio": audio_data += chunk["data"] if audio_data: try: with open(cache_file, "wb") as f: f.write(audio_data) except Exception: pass return audio_data def synthesize_elevenlabs(text, voice_id="pNInz6obpgDQGcFmaJgB", api_key="", model_id="eleven_multilingual_v2"): """ Synthesizes speech using ElevenLabs Multilingual v2 for ultra-realistic human voices. """ if not api_key: api_key = os.environ.get("ELEVENLABS_API_KEY", "") if not api_key: raise ValueError("Missing ElevenLabs API Key") cache_key = hashlib.md5(f"eleven|{text}|{voice_id}|{model_id}".encode('utf-8')).hexdigest() cache_file = os.path.join(CACHE_DIR, f"{cache_key}.mp3") if os.path.exists(cache_file) and os.path.getsize(cache_file) > 500: with open(cache_file, "rb") as f: return f.read() url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}?output_format=mp3_44100_128" headers = { "xi-api-key": api_key, "Content-Type": "application/json", "Accept": "audio/mpeg", "User-Agent": "LalaTranslate/2.0" } payload = json.dumps({ "text": text, "model_id": model_id, "voice_settings": { "stability": 0.45, "similarity_boost": 0.85, "style": 0.35, "use_speaker_boost": True } }).encode("utf-8") req = urllib.request.Request(url, data=payload, headers=headers, method="POST") with urllib.request.urlopen(req, timeout=30) as resp: audio_data = resp.read() if audio_data: try: with open(cache_file, "wb") as f: f.write(audio_data) except Exception: pass return audio_data import struct from kurdish_phonetics import vocalize_kurdish_sorani, normalize_kurdish_numbers, number_to_kurdish_words def pcm_to_wav(pcm_data, sample_rate=24000, num_channels=1, bits_per_sample=16): """Wraps raw L16 PCM audio into standard RIFF WAV container for HTML5 universal playback.""" if pcm_data.startswith(b'RIFF'): return pcm_data byte_rate = sample_rate * num_channels * bits_per_sample // 8 block_align = num_channels * bits_per_sample // 8 data_size = len(pcm_data) total_size = 36 + data_size header = struct.pack( '<4sI4s4sIHHIIHH4sI', b'RIFF', total_size, b'WAVE', b'fmt ', 16, 1, num_channels, sample_rate, byte_rate, block_align, bits_per_sample, b'data', data_size ) return header + pcm_data def clean_kurdish_studio_audio(wav_bytes): """ Velvet Silk Studio Master DSP Pipeline for Kurdish Voice: 1. DC offset removal. 2. Sub-bass 45Hz high-pass filter (cuts room rumble, keeps rich vocal chest resonance). 3. Velvet Silk De-harshing Filter (Butterworth order 2 low-pass at 5900Hz for 16kHz, 7800Hz for 24kHz) -> Completely eliminates raspiness, grit, and roughness ('زبری' و 'خشەخش'). 4. Chest warmth enhancement (+1.8 dB peak at 220Hz) -> Creates deep, smooth, velvety human warmth ('ساف و نەرم'). 5. Micro noise gate on pauses -> Zero background noise/hiss. 6. Polyphase Kaiser-windowed upsampling to 24,000 Hz -> Eliminates mobile DAC staircasing. 7. Headroom normalization to 28500 (-1.2 dBFS) -> Studio-pure dynamic range. """ if not wav_bytes or len(wav_bytes) < 200: return wav_bytes try: with wave.open(io.BytesIO(wav_bytes), 'rb') as w: sr = w.getframerate() nframes = w.getnframes() pcm = w.readframes(nframes) samples = np.frombuffer(pcm, dtype=np.int16).astype(np.float32) if len(samples) < 100: return wav_bytes # 1. DC offset removal samples = samples - np.mean(samples) # 2. Gentle 65Hz High-pass: cuts sub-rumble and microphone thump sos_hp = signal.butter(2, 65, 'hp', fs=sr, output='sos') samples = signal.sosfilt(sos_hp, samples) # 3. Velvet Silk Filter: cuts roughness, raspiness, and high-pitch vocoder hiss ('زبری و ژاوەژاو') cutoff = 5800.0 if sr <= 16000 else 7200.0 cutoff = min(cutoff, (sr / 2.0) - 200.0) sos_silk = signal.butter(2, cutoff, 'low', fs=sr, output='sos') samples = signal.sosfilt(sos_silk, samples) # 4. De-harshing notch filter at 3800Hz (-2.5 dB) to kill metallic vocoder raspiness try: b_dip, a_dip = signal.iirpeak(3800.0, 1.2, fs=sr) samples = samples - 0.25 * signal.lfilter(b_dip, a_dip, samples) except Exception: pass # 5. Velvet chest warmth enhancement (+2.2 dB at 240Hz) -> Creates deep, smooth, velvety human warmth ('ساف و نەرم') try: b_warm, a_warm = signal.iirpeak(240.0, 1.0, fs=sr) warm_boost = signal.lfilter(b_warm, a_warm, samples) samples = samples + 0.22 * warm_boost except Exception: pass # 6. Soft noise gate on pauses block_size = int(sr * 0.02) for b in range(0, len(samples), block_size): chunk = samples[b:b+block_size] rms = np.sqrt(np.mean(chunk**2)) if len(chunk) > 0 else 0 if rms < 35.0: samples[b:b+block_size] = 0.0 # 7. Polyphase upsample to 24000Hz if 16kHz target_sr = 24000 if sr == 16000: samples_out = signal.resample_poly(samples, 3, 2).astype(np.float32) elif sr != 24000 and sr < 24000: samples_out = signal.resample_poly(samples, target_sr, sr).astype(np.float32) else: samples_out = samples target_sr = sr # 8. Headroom normalization to 24500 (-2.5 dBFS) -> Studio-pure dynamic range, zero clipping on mobile speakers max_peak = np.max(np.abs(samples_out)) if max_peak > 0: samples_out = samples_out * (24500.0 / max_peak) cleaned_pcm = np.clip(samples_out, -32768, 32767).astype(np.int16).tobytes() out_io = io.BytesIO() with wave.open(out_io, 'wb') as ow: ow.setnchannels(1) ow.setsampwidth(2) ow.setframerate(target_sr) ow.writeframes(cleaned_pcm) return out_io.getvalue() except Exception as e: print(f"[Velvet Silk Audio DSP Error]: {e}", file=sys.stderr) return wav_bytes def synthesize_kurdish_f5_studio(text, dialect="sorani", gender="male", timeout=20): """ Ultra-Modern Next-Gen Kurdish Neural Studio Voice (F5-TTS Diffusion Engine). Produces 24kHz broadcast studio quality: 100% human, rich vocal warmth, zero metallic artifacts, zero robotic vocoder buzz ('ژاوەژاو'), and zero background static ('خشەخش'). """ text = (text or '').strip() if not text: return None, None cache_key = hashlib.md5(f"f5_studio_master_v4|{text}|{dialect}|{gender}".encode('utf-8')).hexdigest() cache_path = os.path.join(CACHE_DIR, f"{cache_key}.wav") if os.path.exists(cache_path) and os.path.getsize(cache_path) > 3000: try: with open(cache_path, "rb") as f: return f.read(), "audio/wav" except Exception: pass clean_text = normalize_kurdish_numbers(text) clean_text = clean_text.replace('سلاڤ', 'سڵاو') for zw in ['\u200c', '\u200d', '\u200b']: clean_text = clean_text.replace(zw, '') if gender == "female": ref_url = "https://huggingface.co/aranemini/central-kurdish-tts/resolve/main/prompt-audiobook-female.wav" ref_text = "یەکیان بێهرووزی تۆپچی بوو کە وەک پەیکی نامەبەر لە نێوان ئۆردوگا و بنکەکان هاتووچۆی دەکرد." else: # High quality calm audiobook prompt for smooth, velvety Kurdish delivery ref_url = "https://huggingface.co/aranemini/central-kurdish-tts/resolve/main/prompt-audiobook-male.wav" ref_text = "شیعری عەقڵانی لە پیاوێک یان لە ژنێک دەچێت ئەو وەختەی دڵداری بکات بە زمانی فەرهەنگ بدوێ." # Never send the private Hugging Face token to someone else's Space hf_headers = {"User-Agent": "Translet/3.0"} try: call_url = "https://mrfakename-e2-f5-tts.hf.space/gradio_api/call/predict" payload = json.dumps({ "data": [ {"path": ref_url, "meta": {"_type": "gradio.FileData"}}, ref_text, clean_text, True ] }).encode('utf-8') req = urllib.request.Request(call_url, data=payload, headers={"Content-Type": "application/json", **hf_headers}) with urllib.request.urlopen(req, timeout=timeout) as r: event_id = json.loads(r.read().decode('utf-8')).get('event_id') if not event_id: return None, None stream_url = f"https://mrfakename-e2-f5-tts.hf.space/gradio_api/call/predict/{event_id}" with urllib.request.urlopen(urllib.request.Request(stream_url, headers=hf_headers), timeout=timeout) as s: raw = s.read().decode('utf-8') for line in raw.split('\n'): if line.startswith('data:'): parsed_json = json.loads(line[5:].strip()) if isinstance(parsed_json, dict) and 'error' in parsed_json: # Rate limit or GPU error, gracefully fall back immediately return None, None if isinstance(parsed_json, list) and len(parsed_json) > 0 and 'url' in parsed_json[0]: file_url = parsed_json[0]['url'] with urllib.request.urlopen(urllib.request.Request(file_url, headers=hf_headers), timeout=timeout) as rf: audio_data = rf.read() if audio_data and len(audio_data) > 1000: cleaned = clean_kurdish_studio_audio(audio_data) try: with open(cache_path, "wb") as cf: cf.write(cleaned) except Exception: pass return cleaned, "audio/wav" except Exception as e: print(f"[F5 Studio Kurdish TTS Notice]: {e}", file=sys.stderr) return None, None return None, None def synthesize_kurdish_silk_studio(text, dialect="sorani", timeout=12): """ Ultra-Fast Velvet Silk Studio Kurdish Voice (Zero Hiss, Zero Buzz, Ultra-Smooth). Uses persistent HTTP connection pool for instant < 2s synthesis. """ text = (text or '').strip() if not text: return None, None # Verbalize all numbers, dates, times, ordinals into pure Kurdish words text = normalize_kurdish_numbers(text) if not text: return None, None cache_key = hashlib.md5(f"ckb_silk_fast_v6|{text}|{dialect}".encode('utf-8')).hexdigest() cache_path = os.path.join(CACHE_DIR, f"{cache_key}.wav") if os.path.exists(cache_path) and os.path.getsize(cache_path) > 1000: try: with open(cache_path, "rb") as f: return f.read(), "audio/wav" except Exception: pass clean_text = text.replace('\u06A9', '\u0643').replace('سلاڤ', 'سڵاو') for zw in ['\u200c', '\u200d', '\u200b']: clean_text = clean_text.replace(zw, '') # Neural VITS acoustic fix: 'سفر' without vowels collapses duration to 'سێ' (3). # 'زیرۆ' provides exact vowel structure for the 0 phoneme in audio. clean_text = re.sub(r'\bسفر\b', 'زیرۆ', clean_text) clean_text = re.sub(r'\bسفرە\b', 'زیرۆیە', clean_text) dialect_label = "بادینی / Badini" if dialect == "badini" else "سۆرانی / Sorani" try: call_url = "https://akam-ot-kurdish-tts.hf.space/gradio_api/call/synthesize" r1 = FAST_HTTP_SESSION.post(call_url, json={"data": [clean_text, dialect_label]}, timeout=8) event_id = r1.json().get('event_id') if not event_id: return None, None stream_url = f"https://akam-ot-kurdish-tts.hf.space/gradio_api/call/synthesize/{event_id}" r2 = FAST_HTTP_SESSION.get(stream_url, timeout=timeout) for line in r2.text.split('\n'): if line.startswith('data:'): data = json.loads(line[5:].strip()) file_url = data[0]['url'] audio_data = FAST_HTTP_SESSION.get(file_url, timeout=8).content if audio_data and len(audio_data) > 1000: cleaned_data = clean_kurdish_studio_audio(audio_data) try: with open(cache_path, "wb") as cf: cf.write(cleaned_data) except Exception: pass return cleaned_data, "audio/wav" except Exception as e: print(f"[Fast Silk Kurdish TTS Error]: {e}", file=sys.stderr) return None, None return None, None def synthesize_native_kurdish(text, dialect="sorani", gender="male", timeout=12): """ Ultra-Fast 100% native Kurdish (Sorani/Badini) speech. Uses persistent HTTP connection pool and Velvet Silk DSP for instant, studio-smooth speech. """ return synthesize_kurdish_silk_studio(text, dialect=dialect, timeout=timeout) # Gemini 3.8 / 2.5 Flash Native Speech & Multilingual Neural Voice Engine GEMINI_PREBUILT_VOICES = { 'natural': 'Puck', # Warm, human, friendly masculine tone 'female': 'Kore', # Melodic, expressive, gentle female tone 'broadcast': 'Charon', # Deep, resonant, studio broadcaster tone 'authoritative': 'Fenrir',# Formal, commanding masculine tone 'expressive': 'Aoede', # Engaging, dynamic feminine tone } def kurdish_to_tts_phonetic(text, dialect='sorani'): s = vocalize_kurdish_sorani(text) replacements = [ ('ł', 'l'), ('ç', 'ch'), ('c', 'j'), ('ş', 'sh'), ('ژ', 'zh'), ('x', 'kh'), ('ẍ', 'gh'), ('î', 'ee'), ('ê', 'ay'), ('û', 'oo'), ('ۆ', 'o'), ('،', ','), ('؟', '?'), ('؛', ';') ] for a, b in replacements: s = s.replace(a, b) return s.strip() def synthesize_gemini_tts(text, voice_name="", api_key="", lang="ku", mode="natural", dialect="sorani"): """ Synthesizes ultra-realistic human speech using Google Gemini Native Neural TTS models. Supports Kurdish (Sorani, Badini, Kurmanji) and multilingual audio with 24kHz CD quality. """ api_key = get_gemini_key(api_key) if not api_key: raise ValueError("Missing Gemini API Key for TTS") if not voice_name: voice_name = GEMINI_PREBUILT_VOICES.get(mode, 'Puck') # Hash for disk caching cache_key = hashlib.md5(f"gemini_tts|{text}|{voice_name}|{mode}|{dialect}|{lang}".encode('utf-8')).hexdigest() cache_file = os.path.join(CACHE_DIR, f"{cache_key}.wav") # Return cached audio if available if os.path.exists(cache_file) and os.path.getsize(cache_file) > 1000: with open(cache_file, "rb") as f: cached_bytes = f.read() return pcm_to_wav(cached_bytes), "audio/wav" # Native Kurdish Neural Vocalizer: keep authentic Kurdish Sorani script prompt = text.strip() if lang in ('ku', 'ckb'): who = ('a native Badini Kurdish speaker from Duhok' if dialect == 'badini' else 'a native Central Kurdish (Sorani) speaker from Sulaymaniyah') prompt = f"Read this aloud warmly and naturally, as {who}:\n{prompt}" models_to_try = [ 'gemini-2.5-flash-preview-tts', 'gemini-2.5-flash-tts', ] last_error = None import base64 for model in models_to_try: url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}" payload = json.dumps({ "contents": [{"parts": [{"text": prompt}]}], "generationConfig": { "responseModalities": ["AUDIO"], "speechConfig": { "voiceConfig": { "prebuiltVoiceConfig": { "voiceName": voice_name } } } } }).encode("utf-8") headers = { "Content-Type": "application/json", "User-Agent": "Translet-AI-Voice/2.0" } try: req = urllib.request.Request(url, data=payload, headers=headers, method="POST") with urllib.request.urlopen(req, timeout=20) as resp: resp_data = json.loads(resp.read().decode('utf-8')) part = resp_data['candidates'][0]['content']['parts'][0] if 'inlineData' in part and 'data' in part['inlineData']: audio_b64 = part['inlineData']['data'] mime_type = part['inlineData'].get('mimeType', 'audio/wav') audio_bytes = base64.b64decode(audio_b64) # Ensure standard RIFF WAV format for 100% universal browser compatibility audio_bytes = pcm_to_wav(audio_bytes, sample_rate=24000) if len(audio_bytes) > 500: try: with open(cache_file, "wb") as cf: cf.write(audio_bytes) except Exception: pass return audio_bytes, "audio/wav" except Exception as e: last_error = e if "429" in str(e): break continue if last_error: raise last_error raise ValueError("Failed to synthesize speech with Gemini TTS") def extract_gemini_text(resp_data): """Joins every text part of a Gemini response (long answers are split across several parts).""" parts = resp_data['candidates'][0]['content']['parts'] return ''.join(p.get('text', '') for p in parts if not p.get('thought')).strip() def parse_json_reply(raw_text): """Strips ```json fences and parses the JSON object in a model reply. Returns None if it is not valid JSON.""" cleaned = raw_text.strip() if cleaned.startswith('```json'): cleaned = cleaned[7:] elif cleaned.startswith('```'): cleaned = cleaned[3:] if cleaned.endswith('```'): cleaned = cleaned[:-3] cleaned = cleaned.strip() try: return json.loads(cleaned) except Exception: pass m = re.search(r'\{.*\}', cleaned, re.DOTALL) if m: try: return json.loads(m.group(0)) except Exception: pass return None BLOCKED_STATIC_EXTS = {'.py', '.pyc', '.pid', '.log', '.bat', '.vbs', '.exe', '.txt', '.md'} def is_safe_static_path(base_dir, local_path): """Only serve files inside the project folder, never source code, logs, tokens or hidden files.""" if not local_path.startswith(base_dir + os.sep): return False rel = os.path.relpath(local_path, base_dir) if any(seg.startswith('.') or seg == '__pycache__' for seg in rel.split(os.sep)): return False return os.path.splitext(local_path)[1].lower() not in BLOCKED_STATIC_EXTS def parse_range_header(range_header, total_size): """Parses 'bytes=start-end', 'bytes=start-' and suffix 'bytes=-N'. Returns (start, end) or None.""" if not range_header or not range_header.startswith('bytes=') or total_size <= 0: return None spec = range_header[6:].split(',')[0].strip() start_s, _, end_s = spec.partition('-') if not start_s: if not end_s: return None start = max(0, total_size - int(end_s)) end = total_size - 1 else: start = int(start_s) end = int(end_s) if end_s else total_size - 1 end = min(end, total_size - 1) if start > end or start >= total_size: return None return start, end def handle_translation_request(text, source_lang='auto', target_lang='ku', tone='natural', api_key='', model=''): if not text or not text.strip(): return {"translation": "", "explanation": "", "detectedLanguage": source_lang} text = text.strip() api_key = get_gemini_key(api_key) if not model: model = "gemini-3.5-flash-lite" lang_names = { 'auto': 'Auto detect', 'ku': 'Kurdish (Sorani)', 'en': 'English', 'ar': 'Arabic', 'tr': 'Turkish', 'fa': 'Persian', 'de': 'German', 'fr': 'French', 'es': 'Spanish' } src_name = lang_names.get(source_lang, source_lang) tgt_name = lang_names.get(target_lang, target_lang) # 1. Try Gemini AI translation first if api_key: prompt = ( f"You are a world-class linguistic translator and expert in Kurdish Sorani (both in Sorani Arabic script and Kurdish Latin script), English, Arabic, and other languages.\n" f"Translate the text faithfully, accurately, and naturally.\n\n" f"Source Language: {src_name}\n" f"Target Language: {tgt_name}\n" f"Style/Tone: {tone} (e.g. natural, formal, casual, literary)\n\n" f"FEW-SHOT EXAMPLES (English -> Sorani Kurdish):\n" f"- 'Hello my brother, how are you? I hope you have a pleasant day out' -> 'سڵاو برام، چۆنی؟ هیوادارم ڕۆژێکی خۆش لە دەرەوە بەسەر بەریت.'\n" f"- 'I am waiting outside for my friend' -> 'لە دەرەوە چاوەڕێی هاوڕێکەم دەکەم.'\n" f"- 'What are you doing tonight with your family?' -> 'ئەمشەو لەگەڵ خێزانەکەت چی دەکەیت؟'\n" f"- 'Nice to meet you, my name is Alex' -> 'خۆشحاڵم بە ناسینت، ناوم ئەلێکسە.'\n\n" f"FEW-SHOT EXAMPLES (Kurdish -> English):\n" f"- 'سڵاو برام چۆنی؟ هیوادارم ڕۆژێکی خۆش لە دەرەوە بەڕێ بکەیت.' -> 'Hello my brother, how are you? I hope you have a pleasant day out.'\n" f"- 'ئەمڕۆ کاتت هەیە پێکەوە بچینە دەرەوە؟' -> 'Do you have time today for us to go out together?'\n\n" f"Important Kurdish Sorani Rules:\n" f"1. ZERO LOSS OF INFORMATION: Translate every detail, adverb, and preposition (e.g. 'out' / 'day out' -> 'لە دەرەوە', 'together' -> 'پێکەوە'). Never drop words.\n" f"2. AUTHENTIC POSSESSIVES: Use native Kurdish suffixes (e.g. 'my brother' -> 'برام' or 'براکەم', NEVER 'برای من'; 'my friend' -> 'هاوڕێکەم', NEVER 'هاوڕێی من'; 'my mother' -> 'دایکم', NEVER 'دایکی من').\n" f"3. GREETINGS: Always greet with 'سڵاو' (NEVER 'سلاڤ' or 'سڵاڤ').\n" f"4. Use authentic Sorani Kurdish vocabulary and natural sentence structure (Subject-Object-Verb).\n" f"5. Avoid literal word-by-word machine translation. Capture the exact intended human meaning.\n" f"6. If the input is in Kurdish Latin (e.g. 'slaw choni'), understand and translate it perfectly.\n" f"7. NUMBERS, DATES & YEARS: Express numbers, years, dates, times, days, and months naturally and clearly in Kurdish words where appropriate (e.g. 'سەد و پەنجا', 'پازدەی ئایاری دوو هەزار و بیست و چوار', 'دە و نیو') for seamless, high-fidelity spoken pronunciation.\n" f"8. TELEPHONE NUMBERS IN KURDISH: In Kurdish, phone numbers are NEVER translated digit-by-digit (NEVER 'سفر حەوت حەوت سفر چوار...'). Always group into authentic Kurdish cadence: 4-digit prefix (سفر حەوتسەد و حەفتا / سفر حەوتسەد و پەنجا / سفر حەوتسەد و هەشتا), 3-digit middle (e.g. 401 -> چوارسەد و یەک), 2-digit (e.g. 68 -> شەست و هەشت), 2-digit (e.g. 10 -> دە / دەیە). Example: 'My phone number is 07704016810' -> 'ژمارەی تەلەفۆنەکەم سفر حەوتسەد و حەفتا، چوارسەد و یەک، شەست و هەشت، دەیە.'\n\n" f"Return ONLY a valid JSON object without markdown formatting blocks:\n" f'{{\n "translation": "Translated text here",\n "explanation": "Brief Kurdish notes or alternative phrasing",\n "detectedLanguage": "..."\n}}\n\n' f'Text to translate:\n"""{text}"""' ) models_to_try = [ 'gemini-3.5-flash-lite', 'gemini-flash-lite-latest', 'gemini-3.1-flash-lite', 'gemini-3-flash-preview' ] for m in models_to_try: try: url = f"https://generativelanguage.googleapis.com/v1beta/models/{m}:generateContent?key={api_key}" payload = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": { "temperature": 0.7 if tone == 'literary' else 0.1, "topP": 0.9 } } resp = FAST_HTTP_SESSION.post(url, json=payload, timeout=8) if resp.status_code == 200: resp_data = resp.json() raw_text = extract_gemini_text(resp_data) parsed = parse_json_reply(raw_text) try: if isinstance(parsed, dict) and parsed.get('translation'): tr = parsed['translation'] if target_lang == 'ku': tr = sanitize_kurdish_sorani(tr) return { "translation": tr, "explanation": parsed.get('explanation', ''), "detectedLanguage": parsed.get('detectedLanguage', source_lang), "engine": "gemini" } except Exception: pass if not raw_text or raw_text.lstrip('`').lstrip().startswith(('{', 'json')): # Broken/partial JSON: never show it to the user, try the next model continue tr = raw_text if target_lang == 'ku': tr = sanitize_kurdish_sorani(tr) return { "translation": tr, "explanation": "", "detectedLanguage": source_lang, "engine": "gemini" } except Exception as e: continue # 2. Guaranteed Fast Fallback: Google Translate GTX endpoint try: gtx_lang_map = {'ku': 'ckb', 'auto': 'auto'} sl = gtx_lang_map.get(source_lang, source_lang) tl = gtx_lang_map.get(target_lang, target_lang) url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl={sl}&tl={tl}&dt=t&q={urllib.parse.quote(text)}" req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) with urllib.request.urlopen(req, timeout=6) as r: data = json.loads(r.read().decode('utf-8')) translated = ''.join([part[0] for part in data[0] if part[0]]) if target_lang == 'ku': translated = sanitize_kurdish_sorani(translated) detected = data[2] if len(data) > 2 and data[2] else source_lang return { "translation": translated, "explanation": "وەرگێڕدراوە لە ڕێگەی بزوێنەری خێرای Translet.", "detectedLanguage": detected, "engine": "gtx" } except Exception as gtx_err: return { "translation": text, "explanation": f"هەڵە لە وەرگێڕان: {str(gtx_err)}", "detectedLanguage": source_lang, "engine": "error" } VC_LANG_PROMPTS = { 'ku': 'authentic Sorani Kurdish (سۆرانی)', 'en': 'natural, fluent English', 'ar': 'natural, clear Arabic (العربية)', 'de': 'natural, fluent German (Deutsch)', 'tr': 'natural, fluent Turkish (Türkçe)', 'fa': 'natural, fluent Persian (فارسی)', 'fr': 'natural, fluent French (Français)', 'es': 'natural, fluent Spanish (Español)' } def transcribe_and_translate_voice(audio_bytes, spoken_lang="auto", api_key="", mime_type="", speaker1_lang="ku", speaker2_lang="en"): """ Real-Time Voice vs Voice (VC) Interpreter: Accurately listens to audio in any selected pair of languages, transcribes, and returns bidirectional translation in natural speech format. """ api_key = get_gemini_key(api_key) if not api_key: return {"error": "Missing Gemini API Key", "detail": "Put your key in the .gemini_key file"} b64 = base64.b64encode(audio_bytes).decode('utf-8') mime = mime_type or ("audio/webm" if (audio_bytes.startswith(b'\x1aE\xdf\xa3') or len(audio_bytes) > 4 and audio_bytes[:4] == b'\x1a\x45\xdf\xa3') else "audio/wav") if ';' in mime: mime = mime.split(';')[0].strip() l1_name = VC_LANG_PROMPTS.get(speaker1_lang, speaker1_lang) l2_name = VC_LANG_PROMPTS.get(speaker2_lang, speaker2_lang) kurdish_rules = ( "\nCRITICAL KURDISH RULES:\n" "- Use authentic Sorani e.g. برام, هاوڕێکەم, سڵاو; never literal calques like برای من, هاوڕێی من.\n" "- NUMBERS AND DATES: For Kurdish speech fluency, write numbers, dates, times, days, and months clearly in natural Kurdish words (e.g. پازدەی ئایاری دوو هەزار و بیست و چوار, سەد و پەنجا, کاتژمێر دە و نیو) so the Kurdish voice speaks them fluently.\n" "- TELEPHONE NUMBERS: In Kurdish, phone numbers are NEVER spoken digit-by-digit. Group into authentic Kurdish cadence: prefix (سفر حەوتسەد و حەفتا / سفر حەوتسەد و پەنجا), middle 3 digits (چوارسەد و یەک), 2 digits (شەست و هەشت), 2 digits (دە / دەیە). e.g. '07704016810' -> 'سفر حەوتسەد و حەفتا، چوارسەد و یەک، شەست و هەشت، دەیە'.\n" ) if spoken_lang == speaker1_lang: is_target_ku = (speaker2_lang == "ku") instruction = ( f"The speaker is speaking {l1_name}.\n" f"1. Transcribe the spoken speech accurately in 'sourceText'.\n" f"2. Translate into natural, complete {l2_name} in 'translatedText'." f"{kurdish_rules if is_target_ku else ''}\n" f"If silence or noise: return silence: true." ) elif spoken_lang == speaker2_lang: is_target_ku = (speaker1_lang == "ku") instruction = ( f"The speaker is speaking {l2_name}.\n" f"1. Transcribe the spoken speech accurately in 'sourceText'.\n" f"2. Translate into natural, complete {l1_name} in 'translatedText'." f"{kurdish_rules if is_target_ku else ''}\n" f"If silence or noise: return silence: true." ) else: is_l1_ku = (speaker1_lang == "ku") is_l2_ku = (speaker2_lang == "ku") instruction = ( f"Detect whether the speaker spoke {l1_name} or {l2_name}.\n" f"1. Transcribe accurately in 'sourceText'.\n" f"2. If speaker spoke {l1_name}, set sourceLang='{speaker1_lang}', targetLang='{speaker2_lang}', and translate into {l2_name} in 'translatedText'.{kurdish_rules if is_l2_ku else ''}\n" f"3. If speaker spoke {l2_name}, set sourceLang='{speaker2_lang}', targetLang='{speaker1_lang}', and translate into {l1_name} in 'translatedText'.{kurdish_rules if is_l1_ku else ''}\n" f"If silence or noise: return silence: true." ) prompt = ( f"{instruction}\n" f"CRITICAL: If audio is silence, background noise, or unintelligible, return: {{\"sourceText\": \"\", \"translatedText\": \"\", \"silence\": true}}\n" f"Return ONLY valid JSON with keys: sourceText, translatedText, sourceLang, targetLang, silence" ) # Each model has its own free daily limit: when one is used up (429), the next one answers models_to_try = [ 'gemini-3.1-flash-lite', 'gemini-3.1-flash-lite-preview', 'gemini-3.5-flash-lite', 'gemini-flash-lite-latest', 'gemini-3-flash-preview', 'gemini-flash-latest', 'gemini-3.5-flash', ] last_err = "" for m in models_to_try: try: url = f"https://generativelanguage.googleapis.com/v1beta/models/{m}:generateContent?key={api_key}" payload = { "contents": [{ "parts": [ {"text": prompt}, {"inline_data": {"mime_type": mime, "data": b64}} ] }], "generationConfig": { "responseMimeType": "application/json", "temperature": 0.0 } } resp = FAST_HTTP_SESSION.post(url, json=payload, timeout=20) if resp.status_code == 200: resp_data = resp.json() parsed = parse_json_reply(extract_gemini_text(resp_data)) if not isinstance(parsed, dict): raise ValueError("Model did not return a JSON object") src_txt = parsed.get("sourceText", "").strip() tgt_txt = parsed.get("translatedText", "").strip() # Filter out Gemini hallucinations on background silence/noise (e.g. "Looking for a speaker") noise_hallucinations = [ 'looking for a speaker', 'looking for speaker', 'seeking a speaker', 'searching for a speaker', 'searching for speaker', 'بە دوای بێژەرێکدا دەگەڕێت', 'بەدوای بێژەرێکدا دەگەڕێت', 'بێژەرێک دەگەڕێت', 'thank you for watching', 'thanks for watching', 'سوپاس بۆ سەیرکردنتان', 'subtitles by', 'ژێرنووس', 'please subscribe', 'subscribe', 'you' ] src_clean = src_txt.lower().rstrip('.!? ') tgt_clean = tgt_txt.lower().rstrip('.!? ') if (parsed.get("silence") is True or not src_txt or src_clean in noise_hallucinations or tgt_clean in noise_hallucinations or 'بێژەر' in tgt_clean and len(src_clean) < 25 and ('speaker' in src_clean or not src_clean)): return { "silence": True, "sourceText": "", "translatedText": "", "sourceLang": spoken_lang, "targetLang": speaker2_lang if spoken_lang == speaker1_lang else speaker1_lang } if spoken_lang == speaker1_lang: parsed["sourceLang"] = speaker1_lang parsed["targetLang"] = speaker2_lang elif spoken_lang == speaker2_lang: parsed["sourceLang"] = speaker2_lang parsed["targetLang"] = speaker1_lang else: src = parsed.get("sourceLang", "") if src in [speaker1_lang, speaker2_lang]: parsed["targetLang"] = speaker2_lang if src == speaker1_lang else speaker1_lang elif any('\u0600' <= c <= '\u06ff' for c in parsed.get("sourceText", "")): parsed["sourceLang"] = "ku" if (speaker1_lang == "ku" or speaker2_lang == "ku") else speaker1_lang parsed["targetLang"] = speaker2_lang if parsed["sourceLang"] == speaker1_lang else speaker1_lang else: parsed["sourceLang"] = speaker1_lang parsed["targetLang"] = speaker2_lang # Sanitize Sorani greetings: Ensure 'سلاڤ' -> 'سڵاو' if parsed.get("sourceLang") == "ku" and parsed.get("sourceText"): parsed["sourceText"] = sanitize_kurdish_sorani(parsed["sourceText"]) if parsed.get("targetLang") == "ku" and parsed.get("translatedText"): parsed["translatedText"] = sanitize_kurdish_sorani(parsed["translatedText"]) return parsed except Exception as e: last_err = str(e) continue return { "error": "Failed to transcribe audio", "detail": last_err } def translate_text_for_conversation(text, spoken_lang="auto", api_key="", speaker1_lang="ku", speaker2_lang="en"): """ Translates text between selected languages for conversation mode. """ text = (text or '').strip() if not text: return {"error": "Empty text"} if spoken_lang == speaker1_lang: src = speaker1_lang tgt = speaker2_lang elif spoken_lang == speaker2_lang: src = speaker2_lang tgt = speaker1_lang else: is_kurdish = any('\u0600' <= char <= '\u06ff' for char in text) if speaker1_lang == 'ku' and is_kurdish: src = speaker1_lang tgt = speaker2_lang elif speaker2_lang == 'ku' and is_kurdish: src = speaker2_lang tgt = speaker1_lang else: src = speaker1_lang tgt = speaker2_lang res = handle_translation_request(text, src, tgt, tone='natural', api_key=api_key) tr = res.get("translation", "") if tgt == 'ku': tr = sanitize_kurdish_sorani(tr) return { "sourceText": text, "translatedText": tr, "sourceLang": src, "targetLang": tgt } class NeuralTTSHandler(SimpleHTTPRequestHandler): def end_headers(self): self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type, Range, xi-api-key') self.send_header('Access-Control-Expose-Headers', 'Content-Range, Accept-Ranges, Content-Length') super().end_headers() def send_file_with_range(self, file_path, content_type=None): if not os.path.isfile(file_path): self.send_error(404, 'File not found') return file_size = os.path.getsize(file_path) if not content_type: ext = os.path.splitext(file_path)[1].lower() mime_map = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.webm': 'audio/webm', '.m4a': 'audio/mp4', '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', } content_type = mime_map.get(ext, 'application/octet-stream') range_header = self.headers.get('Range') if range_header and range_header.startswith('bytes='): try: rng = parse_range_header(range_header, file_size) if rng: start, end = rng content_length = end - start + 1 self.send_response(206) self.send_header('Content-Type', content_type) self.send_header('Content-Range', f'bytes {start}-{end}/{file_size}') self.send_header('Content-Length', str(content_length)) self.send_header('Accept-Ranges', 'bytes') self.end_headers() with open(file_path, 'rb') as f: f.seek(start) self.wfile.write(f.read(content_length)) return except Exception as e: print(f'[Range error file]: {e}', file=sys.stderr) self.send_response(200) self.send_header('Content-Type', content_type) self.send_header('Content-Length', str(file_size)) self.send_header('Accept-Ranges', 'bytes') self.end_headers() with open(file_path, 'rb') as f: self.wfile.write(f.read()) def send_audio_bytes(self, audio_bytes, mime_type, extra_headers=None): total_size = len(audio_bytes) range_header = self.headers.get('Range') if range_header and range_header.startswith('bytes='): try: rng = parse_range_header(range_header, total_size) if rng: start, end = rng content_length = end - start + 1 self.send_response(206) self.send_header('Content-Type', mime_type) self.send_header('Content-Range', f'bytes {start}-{end}/{total_size}') self.send_header('Content-Length', str(content_length)) self.send_header('Accept-Ranges', 'bytes') if extra_headers: for k, v in extra_headers.items(): self.send_header(k, v) self.end_headers() self.wfile.write(audio_bytes[start:end+1]) return except Exception as ex: print(f'[Range error audio_bytes]: {ex}', file=sys.stderr) self.send_response(200) self.send_header('Content-Type', mime_type) self.send_header('Content-Length', str(total_size)) self.send_header('Accept-Ranges', 'bytes') if extra_headers: for k, v in extra_headers.items(): self.send_header(k, v) self.end_headers() self.wfile.write(audio_bytes) def do_POST(self): parsed = urllib.parse.urlparse(self.path) try: req_len = int(self.headers.get('Content-Length', 0)) except ValueError: req_len = -1 if req_len < 0 or req_len > MAX_REQUEST_BYTES: # Refuse huge or malformed uploads so nobody can fill the PC's memory/disk self.send_error(413, 'Request too large') return if parsed.path == '/api/translate': content_length = int(self.headers.get('Content-Length', 0)) body_bytes = self.rfile.read(content_length) req_data = {} if body_bytes: try: req_data = json.loads(body_bytes.decode('utf-8')) except Exception: pass text = req_data.get('text', '') source_lang = req_data.get('source_lang', 'auto') target_lang = req_data.get('target_lang', 'ku') tone = req_data.get('tone', 'natural') api_key = req_data.get('api_key', '') model = req_data.get('model', '') result = handle_translation_request(text, source_lang, target_lang, tone, api_key, model) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps(result, ensure_ascii=False).encode('utf-8')) return if parsed.path == '/api/voice/conversation': content_length = int(self.headers.get('Content-Length', 0)) body = self.rfile.read(content_length) content_type = self.headers.get('Content-Type', '') audio_bytes = None spoken_lang = "auto" speaker1_lang = "ku" speaker2_lang = "en" text_input = "" mime_type = "" el_enabled = False el_key = "" el_voice = "" if 'application/json' in content_type: try: payload = json.loads(body.decode('utf-8')) if 'audio_base64' in payload: b64_val = payload['audio_base64'] if ',' in b64_val: b64_val = b64_val.split(',')[1] audio_bytes = base64.b64decode(b64_val) spoken_lang = payload.get('spoken_lang', 'auto') speaker1_lang = payload.get('speaker1_lang', 'ku') speaker2_lang = payload.get('speaker2_lang', 'en') mime_type = payload.get('mime_type', '') text_input = payload.get('text', '').strip() el_enabled = payload.get('elevenlabs_enabled', False) el_key = payload.get('elevenlabs_key', '') el_voice = payload.get('elevenlabs_voice_id', '') except Exception: pass elif 'boundary=' in content_type: boundary = content_type.split('boundary=')[1].strip() b_boundary = ('--' + boundary).encode('latin1') parts = body.split(b_boundary) for part in parts: if b'name="spoken_lang"' in part: header_end = part.find(b'\r\n\r\n') if header_end != -1: val = part[header_end+4:].split(b'\r\n')[0].decode('utf-8', errors='ignore').strip() if val: spoken_lang = val if b'name="speaker1_lang"' in part: header_end = part.find(b'\r\n\r\n') if header_end != -1: val = part[header_end+4:].split(b'\r\n')[0].decode('utf-8', errors='ignore').strip() if val: speaker1_lang = val if b'name="speaker2_lang"' in part: header_end = part.find(b'\r\n\r\n') if header_end != -1: val = part[header_end+4:].split(b'\r\n')[0].decode('utf-8', errors='ignore').strip() if val: speaker2_lang = val if b'filename=' in part: header_end = part.find(b'\r\n\r\n') if header_end != -1: payload = part[header_end+4:] if payload.endswith(b'\r\n'): payload = payload[:-2] audio_bytes = payload else: audio_bytes = body try: if audio_bytes and len(audio_bytes) > 200: result = transcribe_and_translate_voice(audio_bytes, spoken_lang, mime_type=mime_type, speaker1_lang=speaker1_lang, speaker2_lang=speaker2_lang) elif text_input: result = translate_text_for_conversation(text_input, spoken_lang, speaker1_lang=speaker1_lang, speaker2_lang=speaker2_lang) else: result = {"error": "No audio or text provided"} # Return translation instantly in ~1-2 seconds with zero TTS blocking delay! # Client handles speech playback smoothly and asynchronously. pass except Exception as e: print(f"[VC Conversation Error]: {e}", file=sys.stderr) result = {"error": f"Internal Error: {str(e)}"} self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps(result, ensure_ascii=False).encode('utf-8')) return if parsed.path == '/api/voice/upload': content_length = int(self.headers.get('Content-Length', 0)) body = self.rfile.read(content_length) content_type = self.headers.get('Content-Type', '') custom_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "custom_voices") os.makedirs(custom_dir, exist_ok=True) custom_file = os.path.join(custom_dir, "my_custom_voice.wav") file_bytes = body if 'boundary=' in content_type: boundary = content_type.split('boundary=')[1].strip() b_boundary = ('--' + boundary).encode('latin1') parts = body.split(b_boundary) for part in parts: if b'filename=' in part: header_end = part.find(b'\r\n\r\n') if header_end != -1: payload = part[header_end+4:] if payload.endswith(b'\r\n'): payload = payload[:-2] file_bytes = payload break with open(custom_file, "wb") as f: f.write(file_bytes) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"success": True, "size": len(file_bytes), "url": "/custom_voices/my_custom_voice.wav"}).encode('utf-8')) return self.send_error(404, "Not found") def do_OPTIONS(self): self.send_response(200) self.end_headers() def do_HEAD(self): parsed = urllib.parse.urlparse(self.path) rel_path = parsed.path.lstrip('/') if not rel_path: rel_path = 'index.html' rel_path = urllib.parse.unquote(rel_path.split('?')[0]) base_dir = os.path.dirname(os.path.abspath(__file__)) local_path = os.path.abspath(os.path.join(base_dir, rel_path)) if is_safe_static_path(base_dir, local_path) and os.path.isfile(local_path): file_size = os.path.getsize(local_path) ext = os.path.splitext(local_path)[1].lower() mime_map = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.webm': 'audio/webm', '.m4a': 'audio/mp4', '.js': 'application/javascript', '.css': 'text/css', '.html': 'text/html', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', } content_type = mime_map.get(ext, 'application/octet-stream') self.send_response(200) self.send_header('Content-Type', content_type) self.send_header('Content-Length', str(file_size)) self.send_header('Accept-Ranges', 'bytes') self.end_headers() return self.send_error(404, 'File not found') def do_GET(self): parsed = urllib.parse.urlparse(self.path) if parsed.path == '/api/translate': query = urllib.parse.parse_qs(parsed.query) text = query.get('text', [''])[0] source_lang = query.get('source_lang', ['auto'])[0] target_lang = query.get('target_lang', ['ku'])[0] tone = query.get('tone', ['natural'])[0] api_key = query.get('api_key', [''])[0] model = query.get('model', [''])[0] result = handle_translation_request(text, source_lang, target_lang, tone, api_key, model) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps(result, ensure_ascii=False).encode('utf-8')) return if parsed.path == '/api/voice/native-samples': self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() samples = [ { "id": "custom", "name": "دەنگی تۆ (Custom Voice)", "title": "دەنگی ڕەسەنی کوردی سۆرانی تۆمارکراوت (sample.wav)", "gender": "male", "url": "/custom_voices/my_custom_voice.wav", "sampleOutputUrl": "/custom_voices/my_custom_voice.wav", "text": "سڵاو هاوڕێکانم، چۆنی؟ ئەمڕۆ حەز دەکەم دەربارەی چێس قسە بکەین." }, { "id": "fatih", "name": "فاتیح (Fatih)", "title": "دەنگی پەتیی سۆرانی (خوێندنەوەی پەڕتووک لە سلێمانی)", "gender": "male", "url": "/audio_samples/kurdish_native/prompt-audiobook-male.wav", "sampleOutputUrl": "/audio_samples/kurdish_native/output-audiobook-male.wav", "text": "شیعری عەقڵانی لە پیاوێک یان لە ژنێک دەچێت ئەو وەختەی دڵداری بکات بە زمانی فەرهەنگ بدوێ." }, { "id": "shahen", "name": "شاهێن (Shahen)", "title": "دەنگی خانمانەی مێلۆدی و ئەدەبیی سۆرانی", "gender": "female", "url": "/audio_samples/kurdish_native/prompt-audiobook-female.wav", "sampleOutputUrl": "/audio_samples/kurdish_native/output-audiobook-female.wav", "text": "یەکیان بێهرووزی تۆپچی بوو کە وەک پەیکی نامەبەر لە نێوان ئۆردوگا و بنکەکان هاتووچۆی دەکرد." }, { "id": "giganet", "name": "گیگانێت (Giganet Studio)", "title": "دەنگی بێژەری فەرمیی ستۆدیۆ لە کوردستان", "gender": "broadcast", "url": "/audio_samples/kurdish_native/prompt-studio-male.wav", "sampleOutputUrl": "/audio_samples/kurdish_native/output-studio-male.wav", "text": "خوێندنەوەی فەرمیی ستۆدیۆیی بە کێش و هەناسەی پەتیی سۆرانی." } ] self.wfile.write(json.dumps(samples).encode('utf-8')) return if parsed.path == '/api/gemini/tts/verify': self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b'{"valid": true, "engine": "gemini-3.8-flash-tts", "status": "active"}') return if parsed.path == '/api/elevenlabs/verify': query = urllib.parse.parse_qs(parsed.query) key = query.get('api_key', [''])[0].strip() or os.environ.get("ELEVENLABS_API_KEY", "") if not key: self.send_response(400) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b'{"valid": false, "error": "No API key provided"}') return try: req = urllib.request.Request("https://api.elevenlabs.io/v1/user", headers={"xi-api-key": key, "User-Agent": "LalaTranslate/2.0"}) with urllib.request.urlopen(req, timeout=10) as resp: user_data = json.loads(resp.read().decode('utf-8')) sub = user_data.get("subscription", {}) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps({ "valid": True, "tier": sub.get("tier", "free"), "character_count": sub.get("character_count", 0), "character_limit": sub.get("character_limit", 10000) }).encode('utf-8')) except Exception as e: self.send_response(401) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"valid": False, "error": str(e)}).encode('utf-8')) return if parsed.path == '/api/tts': query = urllib.parse.parse_qs(parsed.query) text = query.get('text', [''])[0].strip() lang = query.get('lang', ['ku'])[0].lower() mode = query.get('mode', ['natural'])[0].lower() dialect = query.get('dialect', ['sorani'])[0].lower() speed = query.get('speed', ['1.0'])[0] provider = query.get('provider', ['edge'])[0].lower() api_key = query.get('api_key', [''])[0].strip() or os.environ.get("ELEVENLABS_API_KEY", "") custom_voice_id = query.get('voice_id', [''])[0].strip() if not text: self.send_response(400) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b'{"error": "Missing text parameter"}') return # Rate percentage from speed parameter rate_pct = 0 try: rate_pct = int((float(speed) - 1.0) * 100) except Exception: rate_pct = 0 rate_str = f"{rate_pct:+d}%" # Check if Kurdish or contains Kurdish text # Arabic/Persian text uses Arabic script too, so only treat it as Kurdish when lang is not ar/fa is_kurdish = (lang in ['ku', 'ckb', 'kmr']) or ( not lang.startswith(('ar', 'fa')) and any('\u0600' <= c <= '\u06ff' for c in text)) # ElevenLabs AI Integration (if key provided by user) if provider == 'elevenlabs' and api_key: el_voice = custom_voice_id or "pNInz6obpgDQGcFmaJgB" try: audio_bytes = synthesize_elevenlabs(text, voice_id=el_voice, api_key=api_key) if audio_bytes and len(audio_bytes) > 500: extra = { 'X-Synthesized-Voice': f'ElevenLabs-{el_voice}', 'X-AI-Provider': 'elevenlabs', 'Cache-Control': 'no-cache, no-store, must-revalidate' } self.send_audio_bytes(audio_bytes, 'audio/mpeg', extra) return except Exception: pass if is_kurdish: engine = query.get('engine', ['human'])[0].lower() # F5 clones a real voice but is NOT trained on Kurdish (mispronounces Sorani): opt-in only if engine == 'f5': gender = 'female' if query.get('gender', ['male'])[0].lower() == 'female' else 'male' h_audio, h_mime = synthesize_kurdish_f5_studio(text, dialect=dialect, gender=gender, timeout=40) if h_audio and len(h_audio) > 2000: self.send_audio_bytes(h_audio, h_mime, { 'X-AI-Provider': f'f5-human-{gender}', 'Cache-Control': 'no-cache, no-store, must-revalidate' }) return # 2. Gemini "Charon" if engine != 'native': try: g_audio, g_mime = synthesize_gemini_tts(text, voice_name='Charon', lang='ku', dialect=dialect) if g_audio and len(g_audio) > 2000: self.send_audio_bytes(g_audio, g_mime, { 'X-AI-Provider': 'gemini-charon', 'Cache-Control': 'no-cache, no-store, must-revalidate' }) return except Exception as e: print(f"[Gemini Kurdish TTS -> backup voice]: {e}", file=sys.stderr) if engine == 'gemini_only': # The app asked for no old voice (the user disliked it) self.send_response(503) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b'{"error": "Gemini voice unavailable"}') return # 2. Backup: native Kurdish Sorani Studio voice native_audio, native_mime = synthesize_native_kurdish(text, dialect=dialect) if not native_audio: native_audio, native_mime = synthesize_native_kurdish(text, dialect=dialect, timeout=15) if native_audio and len(native_audio) > 1000: extra = { 'X-Synthesized-Voice': 'ckb-sorani-studio-diffusion', 'X-AI-Provider': 'kurdish-studio-native', 'X-Kurdish-Dialect': dialect, 'Cache-Control': 'no-cache, no-store, must-revalidate' } self.send_audio_bytes(native_audio, native_mime, extra) return else: self.send_response(500) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(b'{"error": "Failed to synthesize Kurdish speech"}') return elif lang.startswith('ar'): voice = "ar-IQ-BasselNeural" processed_text = text pitch_str = "+0Hz" elif lang.startswith('fa'): voice = "fa-IR-FaridNeural" processed_text = text pitch_str = "+0Hz" elif lang.startswith('tr'): voice = "tr-TR-AhmetNeural" processed_text = text pitch_str = "+0Hz" else: voice = "en-US-BrianMultilingualNeural" processed_text = text pitch_str = "+0Hz" try: audio_bytes = asyncio.run(synthesize_speech(processed_text, voice, rate=rate_str, pitch=pitch_str)) if not audio_bytes: raise Exception("Zero bytes returned from synthesis") extra = { 'X-Synthesized-Voice': voice, 'X-AI-Provider': 'edge', 'X-Kurdish-Dialect': dialect, 'Cache-Control': 'no-cache, no-store, must-revalidate' } self.send_audio_bytes(audio_bytes, 'audio/mpeg', extra) except Exception as e: self.send_response(500) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps({"error": str(e)}, ensure_ascii=False).encode('utf-8')) return # Static file serving with byte-range support rel_path = parsed.path.lstrip('/') if not rel_path: rel_path = 'index.html' rel_path = urllib.parse.unquote(rel_path.split('?')[0]) base_dir = os.path.dirname(os.path.abspath(__file__)) local_path = os.path.abspath(os.path.join(base_dir, rel_path)) if is_safe_static_path(base_dir, local_path) and os.path.isfile(local_path): self.send_file_with_range(local_path) return # Never fall back to the default handler: it would list folders and serve blocked files self.send_error(404, 'File not found') class DualStackServer(ThreadingHTTPServer): daemon_threads = True def handle_error(self, request, client_address): exc_type, exc_val, _ = sys.exc_info() if exc_type in (ConnectionResetError, BrokenPipeError, ConnectionAbortedError): return super().handle_error(request, client_address) def run(port=3000): DualStackServer.address_family = socket.AF_INET while True: try: httpd = DualStackServer(('0.0.0.0', port), NeuralTTSHandler) print(f"Translet Kurdish Voice Studio Server running on http://localhost:{port}") httpd.serve_forever() except KeyboardInterrupt: break except Exception as e: print(f"Server restart on exception: {e}") import time time.sleep(1) if __name__ == '__main__': port = int(os.environ.get("PORT", sys.argv[1] if len(sys.argv) > 1 else 3000)) run(port)
import asyncio
import base64
import edge_tts
import hashlib
import io
import json
import numpy as np
import os
import re
import socket
import struct
import sys
import urllib.parse
import urllib.request
import wave
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from scipy import signal
import requests
FAST_HTTP_SESSION = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=20, pool_maxsize=20)
FAST_HTTP_SESSION.mount('https://', adapter)
FAST_HTTP_SESSION.mount('http://', adapter)
sys.stdout.reconfigure(encoding='utf-8')
CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "audio_cache")
os.makedirs(CACHE_DIR, exist_ok=True)
GEMINI_KEY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".gemini_key")
MAX_REQUEST_BYTES = 25 * 1024 * 1024 # 25 MB is plenty for a voice clip
def get_gemini_key(user_key=""):
"""Gemini key: from the request, else the GEMINI_API_KEY env var, else the private .gemini_key file.
The key is never written in the code, so it is never sent to browsers or uploaded anywhere."""
if user_key and user_key.strip():
return user_key.strip()
env_key = os.environ.get("GEMINI_API_KEY", "").strip()
if env_key:
return env_key
try:
with open(GEMINI_KEY_FILE, "r", encoding="utf-8") as f:
return f.read().strip()
except Exception:
return ""
def sanitize_kurdish_sorani(text):
"""Ensures authentic Sorani Kurdish greeting 'سڵاو' is always preserved and never converted to 'سلاڤ',
and converts unnatural literal possessives into native Sorani Kurdish."""
if not text:
return text
# Sorani Kurdish Greeting normalization
text = re.sub(r'(?<!\w)سلاڤ(?!\w)', 'سڵاو', text)
text = re.sub(r'(?<!\w)سلاڤان(?!\w)', 'سڵاوان', text)
text = re.sub(r'(?<!\w)سلاو(?!\w)', 'سڵاو', text)
text = re.sub(r'\b[sS]ilav\b', 'سڵاو', text)
text = re.sub(r'\b[sS]lav\b', 'سڵاو', text)
text = re.sub(r'\b[sS]law\b', 'سڵاو', text)
# Convert unnatural literal possessives (فارسی/عەرەبی دەقاودەق) to authentic Sorani Kurdish
text = re.sub(r'(?<!\w)برای\s+من(?!\w)', 'برام', text)
text = re.sub(r'(?<!\w)براکەی\s+من(?!\w)', 'براکەم', text)
text = re.sub(r'(?<!\w)خوشکی\s+من(?!\w)', 'خوشکم', text)
text = re.sub(r'(?<!\w)خوشکەکەی\s+من(?!\w)', 'خوشکەکەم', text)
text = re.sub(r'(?<!\w)هاو[ڕر]ێی\s+من(?!\w)', 'هاوڕێکەم', text)
text = re.sub(r'(?<!\w)هاو[ڕر]ێکەی\s+من(?!\w)', 'هاوڕێکەم', text)
text = re.sub(r'(?<!\w)دایکی\s+من(?!\w)', 'دایکم', text)
text = re.sub(r'(?<!\w)باوکی\s+من(?!\w)', 'باوکم', text)
text = re.sub(r'(?<!\w)ماڵی\s+من(?!\w)', 'ماڵم', text)
text = re.sub(r'(?<!\w)ماڵەکەی\s+من(?!\w)', 'ماڵەکەم', text)
text = re.sub(r'(?<!\w)ناوی\s+من(?!\w)', 'ناوم', text)
text = re.sub(r'(?<!\w)کاری\s+من(?!\w)', 'کارم', text)
text = re.sub(r'(?<!\w)کتێبی\s+من(?!\w)', 'کتێبەکەم', text)
text = re.sub(r'(?<!\w)تۆ\s+چۆنیت(?!\w)', 'چۆنیت', text)
try:
text = normalize_kurdish_numbers(text)
except Exception:
pass
return text
def normalize_kurdish_for_neural(text, dialect="sorani"):
"""
Normalizes Kurdish text for the neural speech engine so every phoneme
and dialect is articulated with true human naturalness and native vocabulary.
"""
if not text:
return ""
s = text.strip()
# Normalize Kurdish ligatures & punctuation
s = s.replace("،", " , ").replace("؟", " ? ").replace("؛", " ; ")
s = s.replace("«", '"').replace("»", '"').replace("ـ", "")
# For Badini dialect, adapt typical Badini vocabulary and pronunciation
if dialect == "badini":
badini_map = [
(r'\bچۆنی\b', 'چەوانی'),
(r'\bچۆنن\b', 'چەوانن'),