khurrameycon commited on
Commit
ff704b5
·
verified ·
1 Parent(s): 9bc8b81

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -0
app.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, UploadFile, File
2
+ from fastapi.responses import FileResponse
3
+ from kokoro import KPipeline
4
+ import soundfile as sf
5
+ import os
6
+ import tempfile
7
+
8
+ app = FastAPI(title="Text-to-Speech Converter")
9
+
10
+ # Initialize pipeline once at startup
11
+ pipeline = KPipeline(lang_code='a')
12
+
13
+ @app.post("/generate_audio/")
14
+ async def generate_audio(text: str = None):
15
+ if not text:
16
+ raise HTTPException(status_code=400, detail="No text provided")
17
+
18
+ try:
19
+ # Create temporary directory
20
+ with tempfile.TemporaryDirectory() as tmpdir:
21
+ # Generate audio
22
+ generator = pipeline(
23
+ text,
24
+ voice='af_heart',
25
+ speed=1,
26
+ split_pattern=r'\n+'
27
+ )
28
+
29
+ # Process first audio segment only (modify as needed)
30
+ i, (gs, ps, audio) = next(enumerate(generator))
31
+
32
+ # Save to temporary file
33
+ output_path = f"{tmpdir}/output.wav"
34
+ sf.write(output_path, audio, 24000)
35
+
36
+ return FileResponse(
37
+ output_path,
38
+ media_type='audio/wav',
39
+ filename="generated_audio.wav"
40
+ )
41
+
42
+ except Exception as e:
43
+ raise HTTPException(status_code=500, detail=str(e))