File size: 22,446 Bytes
ecde958
 
 
 
 
 
 
 
 
 
 
 
 
24d1041
 
ecde958
 
 
 
 
 
 
 
 
 
 
24d1041
ecde958
 
 
 
 
 
 
 
 
 
 
 
 
24d1041
ecde958
51b23f6
 
 
 
 
 
 
 
 
 
 
ecde958
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24d1041
 
ecde958
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24d1041
 
 
 
 
 
 
 
 
 
 
 
ecde958
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51b23f6
 
 
 
 
 
 
 
 
 
24d1041
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecde958
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24d1041
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51b23f6
 
 
 
 
 
 
 
 
 
 
24d1041
 
 
51b23f6
 
 
 
 
24d1041
51b23f6
 
24d1041
 
51b23f6
 
 
 
 
 
 
 
24d1041
 
 
 
 
 
 
 
51b23f6
24d1041
 
 
 
 
 
 
 
51b23f6
24d1041
 
 
 
 
51b23f6
24d1041
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51b23f6
 
ecde958
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
"""
REST API Server for Multi-lingual TTS
FastAPI-based server with OpenAPI documentation

Hackathon API Specification:
- GET /Get_Inference with text, lang, speaker_wav parameters
"""

import os
import io
import time
import logging
import tempfile
import uuid
from typing import Optional, List, Dict
from pathlib import Path
import numpy as np

from fastapi import (
    FastAPI,
    HTTPException,
    Query,
    Response,
    BackgroundTasks,
    UploadFile,
    File,
    Form,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, FileResponse, JSONResponse
from pydantic import BaseModel, Field
import soundfile as sf

from .engine import TTSEngine, TTSOutput
from .config import (
    LANGUAGE_CONFIGS,
    get_available_languages,
    get_available_voices,
    STYLE_PRESETS,
)
from .elevenlabs_service import ElevenLabsService

# Language mapping for XTTS voice cloning
XTTS_LANG_MAP = {
    "english": "en",
    "hindi": "hi",
    "bengali": "bn",
    "gujarati": "gu",
    "marathi": "mr",
    "telugu": "te",
    "kannada": "kn",
}

# Language name to voice key mapping (for hackathon API)
LANG_TO_VOICE = {
    "hindi": "hi_female",
    "bengali": "bn_female",
    "marathi": "mr_female",
    "telugu": "te_female",
    "kannada": "kn_female",
    "bhojpuri": "bho_female",
    "chhattisgarhi": "hne_female",
    "maithili": "mai_female",
    "magahi": "mag_female",
    "english": "en_female",
    "gujarati": "gu_mms",
}

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="Voice Tech for All - Multi-lingual TTS API",
    description="""
    A multi-lingual Text-to-Speech API supporting 10+ Indian languages.
    
    ## Features
    - 10 Indian languages with male/female voices
    - Real-time speech synthesis
    - Text normalization for Indian languages
    - Speed control
    - Multiple audio formats (WAV, MP3)
    
    ## Supported Languages
    Hindi, Bengali, Marathi, Telugu, Kannada, Bhojpuri, 
    Chhattisgarhi, Maithili, Magahi, English
    
    ## Use Case
    Built for an LLM-based healthcare assistant for pregnant mothers
    in low-income communities.
    """,
    version="1.0.0",
    contact={
        "name": "Harshil PAtel",
        "url": "https://harshilpatel.me/#contact",
    },
    license_info={
        "name": "CC BY 4.0",
        "url": "https://creativecommons.org/licenses/by/4.0/",
    },
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize TTS Engine (lazy loading)
_engine: Optional[TTSEngine] = None
_elevenlabs = ElevenLabsService()

# In-memory session voice cache for temporary cloned voice IDs
_voice_session_cache: Dict[str, str] = {}

ALLOWED_AUDIO_TYPES = {
    "audio/wav",
    "audio/x-wav",
    "audio/mpeg",
    "audio/mp3",
}
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024)))


def get_engine() -> TTSEngine:
    """Get or create TTS engine instance"""
    global _engine
    if _engine is None:
        _engine = TTSEngine(device="auto")
    return _engine


# Request/Response Models
class SynthesizeRequest(BaseModel):
    """Request body for text synthesis"""

    text: str = Field(
        ..., description="Text to synthesize", min_length=1, max_length=5000
    )
    voice: str = Field(
        "hi_male", description="Voice key (e.g., hi_male, bn_female, gu_mms)"
    )
    speed: float = Field(1.0, description="Speech speed (0.5-2.0)", ge=0.5, le=2.0)
    pitch: float = Field(1.0, description="Pitch multiplier (0.5-2.0)", ge=0.5, le=2.0)
    energy: float = Field(1.0, description="Energy/volume (0.5-2.0)", ge=0.5, le=2.0)
    style: Optional[str] = Field(
        None, description="Style preset (happy, sad, calm, excited, etc.)"
    )
    normalize: bool = Field(True, description="Apply text normalization")

    class Config:
        schema_extra = {
            "example": {
                "text": "નમસ્તે, હું તમારી કેવી રીતે મદદ કરી શકું?",
                "voice": "gu_mms",
                "speed": 1.0,
                "pitch": 1.0,
                "energy": 1.0,
                "style": "calm",
                "normalize": True,
            }
        }


class SynthesizeResponse(BaseModel):
    """Response metadata for synthesis"""

    success: bool
    duration: float
    sample_rate: int
    voice: str
    text: str
    inference_time: float


class CloneResponse(BaseModel):
    """Response metadata for voice cloning"""

    success: bool
    duration: float
    sample_rate: int
    inference_time: float
    language: str


def _validate_audio_upload(upload: UploadFile, raw_bytes: bytes) -> None:
    if upload is None:
        raise HTTPException(status_code=400, detail="speaker_wav is required")

    filename = (upload.filename or "").lower()
    if not filename.endswith((".wav", ".mp3")):
        raise HTTPException(
            status_code=400, detail="Only .wav or .mp3 files are supported"
        )

    content_type = upload.content_type or ""
    if content_type and content_type not in ALLOWED_AUDIO_TYPES:
        raise HTTPException(
            status_code=400, detail=f"Unsupported content type: {content_type}"
        )

    if len(raw_bytes) == 0:
        raise HTTPException(status_code=400, detail="Uploaded audio file is empty")

    if len(raw_bytes) > MAX_UPLOAD_BYTES:
        raise HTTPException(
            status_code=400,
            detail=f"Audio file too large. Max allowed is {MAX_UPLOAD_BYTES // (1024 * 1024)} MB",
        )


class VoiceInfo(BaseModel):
    """Information about a voice"""

    key: str
    name: str
    language_code: str
    gender: str
    loaded: bool
    downloaded: bool
    model_type: str = "vits"


class HealthResponse(BaseModel):
    """Health check response"""

    status: str
    device: str
    loaded_voices: List[str]
    available_voices: int
    style_presets: List[str]


# API Endpoints
@app.get("/", response_class=JSONResponse)
async def root():
    """API root - welcome message"""
    return {
        "message": "Voice Tech for All - Multi-lingual TTS API",
        "docs": "/docs",
        "health": "/health",
        "synthesize": "/synthesize",
    }


@app.get("/health", response_model=HealthResponse)
async def health_check():
    """Health check endpoint"""
    engine = get_engine()
    return HealthResponse(
        status="healthy",
        device=str(engine.device),
        loaded_voices=engine.get_loaded_voices(),
        available_voices=len(LANGUAGE_CONFIGS),
        style_presets=list(STYLE_PRESETS.keys()),
    )


@app.get("/voices", response_model=List[VoiceInfo])
async def list_voices():
    """List all available voices"""
    engine = get_engine()
    voices = engine.get_available_voices()

    return [
        VoiceInfo(
            key=key,
            name=info["name"],
            language_code=info["code"],
            gender=info["gender"],
            loaded=info["loaded"],
            downloaded=info["downloaded"],
            model_type=info.get("type", "vits"),
        )
        for key, info in voices.items()
    ]


@app.get("/styles")
async def list_styles():
    """List available style presets for prosody control"""
    return {
        "presets": STYLE_PRESETS,
        "description": {
            "speed": "Speech rate multiplier (0.5-2.0)",
            "pitch": "Pitch multiplier (0.5-2.0), >1 = higher",
            "energy": "Volume/energy multiplier (0.5-2.0)",
        },
    }


@app.get("/languages")
async def list_languages():
    """List supported languages"""
    return get_available_languages()


@app.post("/synthesize", response_class=Response)
async def synthesize_audio(request: SynthesizeRequest):
    """
    Synthesize speech from text

    Returns WAV audio file directly
    """
    engine = get_engine()

    # Validate voice
    if request.voice not in LANGUAGE_CONFIGS:
        raise HTTPException(
            status_code=400,
            detail=f"Unknown voice: {request.voice}. Use /voices to see available options.",
        )

    try:
        start_time = time.time()

        # Synthesize
        output = engine.synthesize(
            text=request.text,
            voice=request.voice,
            speed=request.speed,
            pitch=request.pitch,
            energy=request.energy,
            style=request.style,
            normalize_text=request.normalize,
        )

        inference_time = time.time() - start_time

        # Convert to WAV bytes
        buffer = io.BytesIO()
        sf.write(buffer, output.audio, output.sample_rate, format="WAV")
        buffer.seek(0)

        # Return audio with metadata headers
        return Response(
            content=buffer.read(),
            media_type="audio/wav",
            headers={
                "X-Duration": str(output.duration),
                "X-Sample-Rate": str(output.sample_rate),
                "X-Voice": output.voice,
                "X-Style": output.style or "default",
                "X-Inference-Time": str(inference_time),
            },
        )

    except Exception as e:
        logger.error(f"Synthesis error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/synthesize/stream")
async def synthesize_stream(request: SynthesizeRequest):
    """
    Synthesize speech and stream the audio

    Returns streaming WAV audio
    """
    engine = get_engine()

    if request.voice not in LANGUAGE_CONFIGS:
        raise HTTPException(status_code=400, detail=f"Unknown voice: {request.voice}")

    try:
        output = engine.synthesize(
            text=request.text,
            voice=request.voice,
            speed=request.speed,
            pitch=request.pitch,
            energy=request.energy,
            style=request.style,
            normalize_text=request.normalize,
        )

        # Create streaming response
        buffer = io.BytesIO()
        sf.write(buffer, output.audio, output.sample_rate, format="WAV")
        buffer.seek(0)

        return StreamingResponse(
            buffer,
            media_type="audio/wav",
            headers={"Content-Disposition": "attachment; filename=speech.wav"},
        )

    except Exception as e:
        logger.error(f"Streaming error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/generate", response_class=StreamingResponse)
async def generate_with_cloned_voice(
    text: str = Form(...),
    lang: str = Form("english"),
    session_id: Optional[str] = Form(None),
    speaker_wav: Optional[UploadFile] = File(None),
):
    """
    Production-ready temporary voice cloning + speech generation using ElevenLabs.
    """
    lang_lower = (lang or "english").lower().strip()
    local_session_id = session_id or uuid.uuid4().hex
    fallback_voice_id = os.getenv("ELEVENLABS_FALLBACK_VOICE_ID")

    voice_id = _voice_session_cache.get(local_session_id)

    if voice_id is None:
        if speaker_wav is None:
            raise HTTPException(
                status_code=400,
                detail="speaker_wav is required for first request in a session",
            )

        audio_bytes = await speaker_wav.read()
        _validate_audio_upload(speaker_wav, audio_bytes)

        # Re-wrap file for downstream service after validation read
        clone_file = UploadFile(
            filename=speaker_wav.filename,
            file=io.BytesIO(audio_bytes),
            headers=speaker_wav.headers,
        )

        try:
            voice_id = await _elevenlabs.clone_voice(clone_file)
            _voice_session_cache[local_session_id] = voice_id
            logger.info(
                "Cloned ElevenLabs voice for session=%s voice_id=%s",
                local_session_id,
                voice_id,
            )
        except HTTPException as exc:
            if fallback_voice_id:
                logger.warning(
                    "Clone failed for session=%s, using fallback voice",
                    local_session_id,
                )
                voice_id = fallback_voice_id
            else:
                raise exc

    try:
        audio_bytes = _elevenlabs.generate_speech(
            text=text, voice_id=voice_id, language=lang_lower
        )
    except HTTPException as exc:
        if fallback_voice_id and voice_id != fallback_voice_id:
            logger.warning(
                "TTS failed for voice=%s, retrying with fallback voice", voice_id
            )
            audio_bytes = _elevenlabs.generate_speech(
                text=text,
                voice_id=fallback_voice_id,
                language=lang_lower,
            )
        else:
            raise exc

    headers = {
        "Content-Disposition": "attachment; filename=generated.mp3",
        "X-Session-Id": local_session_id,
        "X-Voice-Id": voice_id,
        "X-Provider": "elevenlabs",
    }
    return StreamingResponse(
        io.BytesIO(audio_bytes), media_type="audio/mpeg", headers=headers
    )


@app.post("/clone", response_class=Response)
async def clone_voice(
    text: str = Query(..., description="Text to synthesize with cloned voice"),
    lang: str = Query(
        "english",
        description="Language name (english, hindi, bengali, gujarati, marathi, telugu, kannada)",
    ),
    speed: float = Query(1.0, description="Speech speed", ge=0.5, le=2.0),
    pitch: float = Query(1.0, description="Pitch", ge=0.5, le=2.0),
    energy: float = Query(1.0, description="Energy", ge=0.5, le=2.0),
    style: Optional[str] = Query(None, description="Style preset"),
    session_id: Optional[str] = Query(
        None, description="Session key to reuse cloned voice"
    ),
    speaker_wav: UploadFile = File(
        ..., description="Reference speaker WAV (3-15 seconds recommended)"
    ),
):
    """
    Backward-compatible clone endpoint using ElevenLabs voice cloning.
    """
    lang_lower = lang.lower().strip()
    local_session_id = session_id or uuid.uuid4().hex
    fallback_voice_id = os.getenv("ELEVENLABS_FALLBACK_VOICE_ID")

    if lang_lower not in XTTS_LANG_MAP:
        supported = ", ".join(sorted(XTTS_LANG_MAP.keys()))
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported clone language: {lang}. Supported: {supported}",
        )

    voice_id = _voice_session_cache.get(local_session_id)
    if voice_id is None:
        audio_bytes = await speaker_wav.read()
        _validate_audio_upload(speaker_wav, audio_bytes)
        clone_file = UploadFile(
            filename=speaker_wav.filename,
            file=io.BytesIO(audio_bytes),
            headers=speaker_wav.headers,
        )
        try:
            voice_id = await _elevenlabs.clone_voice(clone_file)
            _voice_session_cache[local_session_id] = voice_id
        except HTTPException as exc:
            if fallback_voice_id:
                voice_id = fallback_voice_id
            else:
                raise exc

    try:
        audio_bytes = _elevenlabs.generate_speech(
            text=text,
            voice_id=voice_id,
            language=lang_lower,
        )
    except HTTPException as exc:
        if fallback_voice_id and voice_id != fallback_voice_id:
            audio_bytes = _elevenlabs.generate_speech(
                text=text,
                voice_id=fallback_voice_id,
                language=lang_lower,
            )
        else:
            raise exc

    return Response(
        content=audio_bytes,
        media_type="audio/mpeg",
        headers={
            "Content-Disposition": "attachment; filename=cloned_output.mp3",
            "X-Language": lang_lower,
            "X-Voice": voice_id,
            "X-Session-Id": local_session_id,
            "X-Provider": "elevenlabs",
        },
    )


@app.get("/synthesize/get")
async def synthesize_get(
    text: str = Query(
        ..., description="Text to synthesize", min_length=1, max_length=1000
    ),
    voice: str = Query("hi_male", description="Voice key"),
    speed: float = Query(1.0, description="Speech speed", ge=0.5, le=2.0),
    pitch: float = Query(1.0, description="Pitch", ge=0.5, le=2.0),
    energy: float = Query(1.0, description="Energy", ge=0.5, le=2.0),
    style: Optional[str] = Query(None, description="Style preset"),
):
    """
    GET endpoint for simple synthesis

    Useful for testing and simple integrations
    """
    request = SynthesizeRequest(
        text=text, voice=voice, speed=speed, pitch=pitch, energy=energy, style=style
    )
    return await synthesize_audio(request)


@app.api_route("/Get_Inference", methods=["GET", "POST"])
async def get_inference(
    text: str = Query(
        ...,
        description="The input text to be converted into speech. For English, text must be lowercase.",
    ),
    lang: str = Query(
        ...,
        description="Language of input text. Supported: bhojpuri, bengali, english, gujarati, hindi, chhattisgarhi, kannada, magahi, maithili, marathi, telugu",
    ),
    speaker_wav: UploadFile = File(
        ...,
        description="A reference WAV file representing the speaker's voice (mandatory per hackathon spec).",
    ),
):
    """
    Hackathon API - Generate speech audio from text

    This endpoint follows the Voice Tech for All hackathon specification.

    Supports both GET and POST methods with multipart form data.

    Parameters:
    - text: Input text to synthesize (query param)
    - lang: Language (query param) - bhojpuri, bengali, english, gujarati, hindi, chhattisgarhi, kannada, magahi, maithili, marathi, telugu
    - speaker_wav: Reference WAV file (multipart file upload, mandatory)

    Returns:
    - 200 OK: WAV audio file as streaming response
    """
    engine = get_engine()

    # Normalize language name
    lang_lower = lang.lower().strip()

    # Enforce lowercase for English text (per spec)
    if lang_lower == "english":
        text = text.lower()

    # Map language to voice
    if lang_lower not in LANG_TO_VOICE:
        supported = list(LANG_TO_VOICE.keys())
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported language: {lang}. Supported languages: {', '.join(supported)}",
        )

    voice = LANG_TO_VOICE[lang_lower]

    # Read speaker_wav (mandatory per spec)
    # Note: Current VITS models don't support voice cloning, but we accept the file
    # for API compatibility and validation. In future, this could be used for voice adaptation.
    try:
        speaker_audio_bytes = await speaker_wav.read()
        logger.info(
            f"Received speaker reference WAV: {len(speaker_audio_bytes)} bytes, filename: {speaker_wav.filename}"
        )
        # Validate it's a valid audio file (basic check)
        if len(speaker_audio_bytes) < 44:  # Minimum WAV header size
            raise HTTPException(
                status_code=400,
                detail="Invalid speaker_wav: file too small to be a valid WAV",
            )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Could not read speaker_wav: {e}")
        raise HTTPException(
            status_code=400, detail=f"Failed to read speaker_wav file: {str(e)}"
        )

    try:
        # Synthesize audio
        output = engine.synthesize(
            text=text,
            voice=voice,
            speed=1.0,
            normalize_text=True,
        )

        # Convert to WAV bytes
        buffer = io.BytesIO()
        sf.write(buffer, output.audio, output.sample_rate, format="WAV")
        buffer.seek(0)

        # Return as streaming response (per spec)
        return StreamingResponse(
            buffer,
            media_type="audio/wav",
            headers={
                "Content-Disposition": "attachment; filename=output.wav",
                "X-Duration": str(output.duration),
                "X-Sample-Rate": str(output.sample_rate),
                "X-Language": lang,
                "X-Voice": voice,
            },
        )

    except Exception as e:
        logger.error(f"Synthesis error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/preload")
async def preload_voice(voice: str):
    """Preload a voice model into memory"""
    engine = get_engine()

    if voice not in LANGUAGE_CONFIGS:
        raise HTTPException(status_code=400, detail=f"Unknown voice: {voice}")

    try:
        engine.load_voice(voice)
        return {"message": f"Voice {voice} loaded successfully"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/unload")
async def unload_voice(voice: str):
    """Unload a voice model from memory"""
    engine = get_engine()
    engine.unload_voice(voice)
    return {"message": f"Voice {voice} unloaded"}


@app.post("/batch")
async def batch_synthesize(
    texts: List[str], voice: str = "hi_male", speed: float = 1.0
):
    """
    Synthesize multiple texts

    Returns a list of base64-encoded audio
    """
    import base64

    engine = get_engine()

    if voice not in LANGUAGE_CONFIGS:
        raise HTTPException(status_code=400, detail=f"Unknown voice: {voice}")

    results = []
    for text in texts:
        output = engine.synthesize(text, voice, speed)

        buffer = io.BytesIO()
        sf.write(buffer, output.audio, output.sample_rate, format="WAV")
        buffer.seek(0)

        results.append(
            {
                "text": text,
                "audio_base64": base64.b64encode(buffer.read()).decode(),
                "duration": output.duration,
            }
        )

    return results


# Startup/Shutdown events
@app.on_event("startup")
async def startup_event():
    """Initialize on startup"""
    logger.info("Starting TTS API server...")
    # Optionally preload default voice
    # get_engine().load_voice("hi_male")


@app.on_event("shutdown")
async def shutdown_event():
    """Cleanup on shutdown"""
    logger.info("Shutting down TTS API server...")


def start_server(host: str = "0.0.0.0", port: int = 8000, reload: bool = False):
    """Start the API server"""
    import uvicorn

    uvicorn.run("src.api:app", host=host, port=port, reload=reload, log_level="info")


if __name__ == "__main__":
    start_server()