Spaces:
Sleeping
Sleeping
| import os | |
| import uuid | |
| import requests | |
| from pathlib import Path | |
| import tempfile | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| elevenlabs_api_key = os.environ["ELEVENLABS_API_KEY"] | |
| voice_id = os.environ["VOICE_ID"] | |
| def generate_tts(text): | |
| url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}" | |
| headers = { | |
| "Accept": "audio/mpeg", | |
| "Content-Type": "application/json", | |
| "xi-api-key": elevenlabs_api_key | |
| } | |
| data = {"text": text} | |
| response = requests.post(url, headers=headers, json=data) | |
| if response.status_code != 200: | |
| raise Exception("TTS generation failed") | |
| output_path = Path(tempfile.gettempdir()) / f"output_{uuid.uuid4().hex}.mp3" | |
| with open(output_path, "wb") as f: | |
| f.write(response.content) | |
| return output_path |