Skip to content

Commit 411f594

Browse files
committed
update fastapi1。
1 parent 310acb8 commit 411f594

2 files changed

Lines changed: 70 additions & 13 deletions

File tree

examples/indextts_fastapi_client.py

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,33 @@ def check_server_health(self) -> bool:
4343
print(f"✗ Cannot connect to server: {e}")
4444
return False
4545

46+
def download_audio(self, file_id: str, save_path: str) -> bool:
47+
"""
48+
从服务器下载音频文件
49+
50+
Args:
51+
file_id: 音频文件ID
52+
save_path: 保存路径
53+
54+
Returns:
55+
是否下载成功
56+
"""
57+
try:
58+
response = self.session.get(
59+
f"{self.base_url}/api/audio/{file_id}",
60+
timeout=30
61+
)
62+
response.raise_for_status()
63+
64+
# 保存文件
65+
with open(save_path, 'wb') as f:
66+
f.write(response.content)
67+
68+
return True
69+
except Exception as e:
70+
print(f"✗ Failed to download audio: {e}")
71+
return False
72+
4673
def generate_tts(
4774
self,
4875
text: str,
@@ -114,22 +141,26 @@ def generate_tts(
114141
print(f"✗ TTS generation failed: {result.get('message')}")
115142
return None
116143

117-
# 获取服务器返回的音频文件路径
118-
server_audio_path = result.get("audio_path")
119-
if not server_audio_path:
120-
print("✗ No audio path in response")
144+
# 获取服务器返回的文件ID
145+
file_id = result.get("file_id")
146+
if not file_id:
147+
print("✗ No file_id in response")
121148
return None
122149

123-
print(f"✓ Audio generated at: {server_audio_path}")
150+
print(f"✓ Audio generated on server with file_id: {file_id}")
124151

125-
# 如果需要保存到指定路径,则复制文件
126-
if save_path is not None and save_path != server_audio_path:
127-
import shutil
128-
os.makedirs(os.path.dirname(save_path) if os.path.dirname(save_path) else '.', exist_ok=True)
129-
shutil.copy2(server_audio_path, save_path)
130-
print(f"✓ Audio copied to: {save_path}")
152+
# 确定本地保存路径
153+
if save_path is None:
154+
save_path = str(self.temp_dir / f"{file_id}.wav")
131155
else:
132-
save_path = server_audio_path
156+
os.makedirs(os.path.dirname(save_path) if os.path.dirname(save_path) else '.', exist_ok=True)
157+
158+
# 从服务器下载音频文件
159+
print(f"📥 Downloading audio to: {save_path}")
160+
if not self.download_audio(file_id, save_path):
161+
return None
162+
163+
print(f"✓ Audio downloaded successfully")
133164

134165
# 播放音频
135166
if play_audio:

examples/indextts_fastapi_server.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ class TTSResponse(BaseModel):
124124
success: bool
125125
message: str
126126
audio_path: Optional[str] = None
127+
file_id: Optional[str] = None
127128

128129

129130
@api_router.get("/")
@@ -134,6 +135,7 @@ async def root():
134135
"version": "1.0.0",
135136
"endpoints": {
136137
"/api/tts": "POST - Generate TTS audio",
138+
"/api/audio/{file_id}": "GET - Download audio file",
137139
"/api/health": "GET - Health check"
138140
}
139141
}
@@ -155,6 +157,29 @@ async def health_check():
155157
temp_dir.mkdir(exist_ok=True)
156158

157159

160+
@api_router.get("/audio/{file_id}")
161+
async def download_audio(file_id: str):
162+
"""
163+
下载生成的音频文件
164+
165+
Args:
166+
file_id: 音频文件ID(不含.wav扩展名)
167+
168+
Returns:
169+
音频文件
170+
"""
171+
audio_path = temp_dir / f"{file_id}.wav"
172+
173+
if not audio_path.exists():
174+
raise HTTPException(status_code=404, detail=f"Audio file not found: {file_id}")
175+
176+
return FileResponse(
177+
path=str(audio_path),
178+
media_type="audio/wav",
179+
filename=f"{file_id}.wav"
180+
)
181+
182+
158183
@api_router.post("/tts", response_model=TTSResponse)
159184
async def generate_tts(request: TTSRequest):
160185
"""
@@ -195,7 +220,8 @@ async def generate_tts(request: TTSRequest):
195220
return TTSResponse(
196221
success=True,
197222
message="TTS generated successfully",
198-
audio_path=output_path
223+
audio_path=output_path,
224+
file_id=file_id
199225
)
200226

201227
except Exception as e:

0 commit comments

Comments
 (0)