Spaces:
Sleeping

File size: 9,654 Bytes
b0fc919
 
 
51fd5c5
 
b0fc919
 
 
 
 
 
 
 
 
 
 
d94ef89
b0fc919
 
 
 
 
 
 
 
 
51fd5c5
 
 
b0fc919
d8df388
 
 
 
 
b0fc919
 
 
 
 
 
 
51fd5c5
 
 
 
b0fc919
51fd5c5
b0fc919
51fd5c5
b0fc919
51fd5c5
b0fc919
51fd5c5
b0fc919
51fd5c5
b0fc919
51fd5c5
b0fc919
51fd5c5
b0fc919
 
51fd5c5
b0fc919
51fd5c5
b0fc919
51fd5c5
 
 
b0fc919
 
 
51fd5c5
1e49acc
b0fc919
51fd5c5
 
b0fc919
 
51fd5c5
 
 
 
1e49acc
51fd5c5
 
 
 
 
 
 
 
1e49acc
 
 
b0fc919
51fd5c5
 
 
 
 
 
b0fc919
1e49acc
 
 
 
 
 
 
 
51fd5c5
 
 
1e49acc
 
 
 
 
 
 
51fd5c5
b0fc919
 
d8df388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0fc919
 
 
 
 
51fd5c5
b0fc919
 
51fd5c5
 
b0fc919
51fd5c5
b0fc919
 
 
 
 
 
51fd5c5
b0fc919
 
 
 
 
 
 
 
 
51fd5c5
b0fc919
51fd5c5
b0fc919
 
51fd5c5
b0fc919
51fd5c5
 
 
 
 
 
 
f5ad6a8
 
 
 
 
 
 
 
 
 
 
51fd5c5
f5ad6a8
 
 
51fd5c5
f5ad6a8
 
 
 
 
 
 
 
 
51fd5c5
 
 
 
 
 
 
 
b0fc919
 
 
 
 
 
51fd5c5
b0fc919
51fd5c5
 
b0fc919
 
51fd5c5
b0fc919
 
 
51fd5c5
 
 
 
 
 
b0fc919
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/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)