Spaces:
Sleeping

edgetts / app.py
michdubai's picture
Update app.py
1e49acc verified
Raw History Blame Contribute Delete
9.65 kB
#!/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 """
<html>
<head><title>Bilingual TTS Bridge - Chinese Female + English Male</title></head>
<body style="font-family: Arial, sans-serif; margin: 40px; text-align: center; background-color: #fafafa;">
<h1 style="color: #4CAF50;">Bilingual Edge-TTS Bridge</h1>
<p style="color: #666;">Chinese Voice: <strong>zh-CN-XiaoxiaoNeural (Female)</strong></p>
<p style="color: #666;">English Voice: <strong>en-US-ChristopherNeural (Male)</strong></p>
<p style="color: #666;">Status: <strong style="color: green;">Running Unlimited Free Tier</strong></p>
<p>API Endpoint: <code>/v1/audio/speech</code></p>
</body>
</html>
"""
@app.post("/v1/audio/speech")
async def tts(request: TTSRequest, authorization: str = Header(None)):
# Authentication check
token = authorization.replace("Bearer ", "") if authorization else None
if token != AUTH_TOKEN:
log("Unauthorized access attempt rejected.")
raise HTTPException(status_code=401, detail="Unauthorized: Invalid API Key.")
raw_text = request.input.strip()
if not raw_text:
return Response(status_code=204)
# Clean markdown
text = clean_markdown(raw_text)
log(f"Processing Text: {text[:100]}... (length: {len(text)})")
try:
# Split text into language-based segments
segments = split_bilingual_text(text)
if not segments:
log("No segments generated")
return Response(status_code=204)
log(f"Split into {len(segments)} segment(s)")
# Process segments with concurrency limiting and retries
semaphore = Semaphore(MAX_CONCURRENT_SEGMENTS)
tasks = [
synthesize_segment_with_semaphore(semaphore, seg["text"], seg["voice"], i)
for i, seg in enumerate(segments)
]
log(f"Processing {len(segments)} segments with concurrency limit of {MAX_CONCURRENT_SEGMENTS}")
results = await asyncio.gather(*tasks)
# Sort results by index and collect audio chunks
audio_chunks = []
failed_segments = []
for index, audio_data, success in sorted(results, key=lambda x: x[0]):
if success and audio_data:
audio_chunks.append(audio_data)
else:
failed_segments.append(index + 1)
# Log results
success_count = len(audio_chunks)
total_count = len(segments)
log(f"Successfully generated {success_count}/{total_count} segments")
if failed_segments:
log(f"Failed segments: {failed_segments}")
if not audio_chunks:
log("No audio generated from any segment")
raise HTTPException(status_code=500, detail="No audio generated")
# Combine all audio chunks
combined_audio = b"".join(audio_chunks)
log(f"Successfully generated {len(combined_audio)} bytes of audio from {len(audio_chunks)} chunk(s)")
headers = {
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
}
return Response(content=combined_audio, media_type="audio/mpeg", headers=headers)
except HTTPException:
raise
except Exception as e:
log(f"CRITICAL EXCEPTION: {str(e)}")
raise HTTPException(status_code=500, detail=f"TTS processing failed: {str(e)}")
@app.get("/v1/audio/voices")
async def voices():
return {
"voices": [
{"name": ZH_VOICE, "language": "zh", "gender": "female"},
{"name": EN_VOICE, "language": "en", "gender": "male"}
]
}
if __name__ == "__main__":
port_env = int(os.getenv("PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port_env, workers=1)