#!/usr/bin/env python3 """ Bilingual Edge-TTS OpenAI-Compatible Bridge for Open WebUI Chinese: zh-CN-XiaoxiaoNeural (Female) English: en-US-ChristopherNeural (Male) """ import os import re import sys import asyncio from fastapi import FastAPI, Response, HTTPException, Header from fastapi.responses import HTMLResponse from pydantic import BaseModel import uvicorn import edge_tts from asyncio import Semaphore app = FastAPI() def log(message: str): print(f"[TTS-LOG] {message}", file=sys.stdout, flush=True) # Secure Token Configuration from HF Secrets AUTH_TOKEN = os.getenv("INTERNAL_TTS_KEY", "your-super-secure-custom-password-here") # Voice Configuration ZH_VOICE = "zh-CN-XiaoxiaoNeural" # Chinese Female EN_VOICE = "en-US-ChristopherNeural" # English Male # Configuration for concurrent processing MAX_CONCURRENT_SEGMENTS = 3 # Process at most 3 segments simultaneously MAX_RETRIES = 3 # Retry failed segments up to 3 times RETRY_DELAY = 1 # Delay between retries in seconds class TTSRequest(BaseModel): input: str model: str = "tts-1" voice: str = "alloy" def clean_markdown(text: str) -> str: """Removes Markdown syntax symbols so TTS reads clean plain text.""" if not text: return "" # Remove code blocks text = re.sub(re.compile(r'```.*?```', re.DOTALL), '', text) # Remove inline code text = re.sub(r'`(.*?)`', r'\1', text) # Remove bold/italic markers text = re.sub(r'\*{1,3}(.*?)\*{1,3}', r'\1', text) # Remove markdown links, keep text text = re.sub(r'\[(.*?)\]\(.*?\)', r'\1', text) # Convert headers to text text = re.sub(r'(?:^|\n)#+\s+(.*)', r'\1.', text) # Remove list bullets text = re.sub(r'(?:^|\n)\s*[\-\*\+]\s+', r'\n', text) # Remove blockquotes text = re.sub(r'(?:^|\n)\s*>\s+', r'\n', text) # Remove or replace slashes text = re.sub(r'(?<=\S)\s*/\s*(?=\S)', ' ', text) text = text.replace('/', '.') # Remove emoji and other non-speakable characters (keep Chinese) text = re.sub(r'[^\x00-\x7F\u4e00-\u9fff\u3000-\u303f\uff00-\uffef]', '', text) # Collapse multiple spaces text = re.sub(r' +', ' ', text) text = re.sub(r'\n+', '\n', text).strip() return text def split_bilingual_text(text: str): """ Split text into segments based on language. Filters out punctuation-only segments. """ if not text: return [] segments = [] current_segment = "" current_lang = None for char in text: # Detect language is_chinese = '\u4e00' <= char <= '\u9fff' or char in ',。!?;:“”‘’、' is_english = char.isascii() or char in '.,!?;:()[]{}' or char.isspace() if is_chinese: lang = "zh" elif is_english: lang = "en" else: # Keep punctuation with current segment if current_lang is not None: current_segment += char continue if current_lang is None: current_lang = lang current_segment = char elif current_lang == lang: current_segment += char else: # Language switch - save current segment if it contains meaningful content if current_segment.strip() and len(current_segment.strip()) > 1: # Check if segment is more than just punctuation if not all(c in '.,!?;:)]}。!?;:)」』' or c.isspace() for c in current_segment.strip()): segments.append({ "text": current_segment.strip(), "voice": ZH_VOICE if current_lang == "zh" else EN_VOICE }) current_lang = lang current_segment = char # Add last segment with same filter if current_segment and current_segment.strip() and len(current_segment.strip()) > 1: if not all(c in '.,!?;:)]}。!?;:)」』' or c.isspace() for c in current_segment.strip()): segments.append({ "text": current_segment.strip(), "voice": ZH_VOICE if current_lang == "zh" else EN_VOICE }) return segments async def synthesize_segment_with_retry(text: str, voice: str, retry_count: int = 0) -> bytes: """Synthesizes a single text segment with retry logic.""" try: communicate = edge_tts.Communicate(text, voice) audio_bytes = b"" async for chunk in communicate.stream(): if chunk["type"] == "audio": audio_bytes += chunk["data"] elif chunk["type"] == "error": raise Exception(f"Edge TTS error: {chunk}") if audio_bytes: return audio_bytes else: raise Exception("No audio data received") except Exception as e: if retry_count < MAX_RETRIES: log(f"Segment failed (attempt {retry_count + 1}/{MAX_RETRIES}): {text[:30]}... Retrying") await asyncio.sleep(RETRY_DELAY) return await synthesize_segment_with_retry(text, voice, retry_count + 1) else: log(f"Segment failed after {MAX_RETRIES} attempts: {text[:50]}...") return b"" async def synthesize_segment_with_semaphore(semaphore: Semaphore, text: str, voice: str, index: int) -> tuple: """Wrapper that uses semaphore to limit concurrency.""" async with semaphore: log(f" Processing segment {index + 1}") audio_data = await synthesize_segment_with_retry(text, voice) success = len(audio_data) > 0 return (index, audio_data, success) @app.get("/", response_class=HTMLResponse) async def root(): return """
Chinese Voice: zh-CN-XiaoxiaoNeural (Female)
English Voice: en-US-ChristopherNeural (Male)
Status: Running Unlimited Free Tier
API Endpoint: /v1/audio/speech