Spaces:
Sleeping
Sleeping
Create narration.py
Browse files- genesis/narration.py +40 -0
genesis/narration.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# genesis/narration.py
|
2 |
+
import os
|
3 |
+
import requests
|
4 |
+
from typing import Optional
|
5 |
+
|
6 |
+
ELEVEN_LABS_API_KEY = os.getenv("ELEVEN_LABS_API_KEY")
|
7 |
+
VOICE_ID = "EXAVITQu4vr4xnSDxMaL" # Default voice; change in ElevenLabs dashboard if needed
|
8 |
+
|
9 |
+
def narrate_text(text: str) -> Optional[str]:
|
10 |
+
"""Convert text to speech using ElevenLabs API and return audio URL."""
|
11 |
+
if not ELEVEN_LABS_API_KEY:
|
12 |
+
print("[Narration] No ElevenLabs API key provided.")
|
13 |
+
return None
|
14 |
+
|
15 |
+
try:
|
16 |
+
url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}"
|
17 |
+
headers = {
|
18 |
+
"xi-api-key": ELEVEN_LABS_API_KEY,
|
19 |
+
"Content-Type": "application/json"
|
20 |
+
}
|
21 |
+
payload = {
|
22 |
+
"text": text,
|
23 |
+
"voice_settings": {
|
24 |
+
"stability": 0.4,
|
25 |
+
"similarity_boost": 0.8
|
26 |
+
}
|
27 |
+
}
|
28 |
+
r = requests.post(url, headers=headers, json=payload, timeout=30)
|
29 |
+
r.raise_for_status()
|
30 |
+
|
31 |
+
# Save audio locally
|
32 |
+
audio_file = "narration.mp3"
|
33 |
+
with open(audio_file, "wb") as f:
|
34 |
+
f.write(r.content)
|
35 |
+
|
36 |
+
# In Spaces, you can serve local files directly
|
37 |
+
return audio_file
|
38 |
+
except Exception as e:
|
39 |
+
print(f"[Narration] Failed: {e}")
|
40 |
+
return None
|