Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:57:28 +08:00
commit e063391898
27 changed files with 3055 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.8"
# dependencies = [
# "elevenlabs",
# "python-dotenv",
# ]
# ///
import os
import sys
from dotenv import load_dotenv
def main():
"""
ElevenLabs Turbo v2.5 TTS Script
Uses ElevenLabs' Turbo v2.5 model for fast, high-quality text-to-speech.
Accepts optional text prompt as command-line argument.
Usage:
- ./eleven_turbo_tts.py # Uses default text
- ./eleven_turbo_tts.py "Your custom text" # Uses provided text
Features:
- Fast generation (optimized for real-time use)
- High-quality voice synthesis
- Stable production model
- Cost-effective for high-volume usage
"""
# Load environment variables
load_dotenv()
# Get API key from environment
api_key = os.getenv("ELEVENLABS_API_KEY")
if not api_key:
print("❌ Error: ELEVENLABS_API_KEY not found in environment variables")
print("Please add your ElevenLabs API key to .env file:")
print("ELEVENLABS_API_KEY=your_api_key_here")
sys.exit(1)
try:
from elevenlabs import play
from elevenlabs.client import ElevenLabs
# Initialize client
elevenlabs = ElevenLabs(api_key=api_key)
print("🎙️ ElevenLabs Turbo v2.5 TTS")
print("=" * 40)
# Get text from command line argument or use default
if len(sys.argv) > 1:
text = " ".join(sys.argv[1:]) # Join all arguments as text
else:
text = "The first move is what sets everything in motion."
print(f"🎯 Text: {text}")
print("🔊 Generating and playing...")
try:
# Generate and play audio directly
audio = elevenlabs.text_to_speech.convert(
text=text,
voice_id="9BWtsMINqrJLrRacOk9x", # Aria voice
model_id="eleven_turbo_v2_5",
output_format="mp3_44100_128",
)
play(audio)
print("✅ Playback complete!")
except Exception as e:
print(f"❌ Error: {e}")
except ImportError:
print("❌ Error: elevenlabs package not installed")
print("This script uses UV to auto-install dependencies.")
print("Make sure UV is installed: https://docs.astral.sh/uv/")
sys.exit(1)
except Exception as e:
print(f"❌ Unexpected error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()

107
hooks/utils/tts/openai_tts.py Executable file
View File

@@ -0,0 +1,107 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.8"
# dependencies = [
# "openai",
# "openai[voice_helpers]",
# "python-dotenv",
# ]
# ///
import asyncio
import os
import subprocess
import sys
import tempfile
from dotenv import load_dotenv
async def main():
"""
OpenAI TTS Script
Uses OpenAI's latest TTS model for high-quality text-to-speech.
Accepts optional text prompt as command-line argument.
Usage:
- ./openai_tts.py # Uses default text
- ./openai_tts.py "Your custom text" # Uses provided text
Features:
- OpenAI gpt-4o-mini-tts model (latest)
- Nova voice (engaging and warm)
- Streaming audio with instructions support
- Live audio playback via afplay (macOS)
"""
# Load environment variables
load_dotenv()
# Get API key from environment
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("❌ Error: OPENAI_API_KEY not found in environment variables")
print("Please add your OpenAI API key to .env file:")
print("OPENAI_API_KEY=your_api_key_here")
sys.exit(1)
try:
from openai import AsyncOpenAI
# Initialize OpenAI client
openai = AsyncOpenAI(api_key=api_key)
print("🎙️ OpenAI TTS")
print("=" * 20)
# Get text from command line argument or use default
if len(sys.argv) > 1:
text = " ".join(sys.argv[1:]) # Join all arguments as text
else:
text = "Today is a wonderful day to build something people love!"
print(f"🎯 Text: {text}")
print("🔊 Generating and streaming...")
try:
# Generate and stream audio using OpenAI TTS
async with openai.audio.speech.with_streaming_response.create(
model="gpt-4o-mini-tts",
voice="nova",
input=text,
instructions="Speak in a cheerful, positive yet professional tone.",
response_format="mp3",
) as response:
# Create a temporary file to store the audio
with tempfile.NamedTemporaryFile(
delete=False, suffix=".mp3"
) as temp_file:
# Write the audio stream to the temporary file
async for chunk in response.iter_bytes():
temp_file.write(chunk)
temp_file_path = temp_file.name
try:
# Play the audio using afplay
subprocess.run(["afplay", temp_file_path], check=True)
print("✅ Playback complete!")
finally:
# Clean up the temporary file
os.unlink(temp_file_path)
except Exception as e:
print(f"❌ Error: {e}")
except ImportError:
print("❌ Error: Required package not installed")
print("This script uses UV to auto-install dependencies.")
print("Make sure UV is installed: https://docs.astral.sh/uv/")
sys.exit(1)
except Exception as e:
print(f"❌ Unexpected error: {e}")
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())

77
hooks/utils/tts/pyttsx3_tts.py Executable file
View File

@@ -0,0 +1,77 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.8"
# dependencies = [
# "pyttsx3",
# ]
# ///
import random
import sys
def main():
"""
pyttsx3 TTS Script
Uses pyttsx3 for offline text-to-speech synthesis.
Accepts optional text prompt as command-line argument.
Usage:
- ./pyttsx3_tts.py # Uses default text
- ./pyttsx3_tts.py "Your custom text" # Uses provided text
Features:
- Offline TTS (no API key required)
- Cross-platform compatibility
- Configurable voice settings
- Immediate audio playback
"""
try:
import pyttsx3
# Initialize TTS engine
engine = pyttsx3.init()
# Configure engine settings
engine.setProperty("rate", 180) # Speech rate (words per minute)
engine.setProperty("volume", 0.8) # Volume (0.0 to 1.0)
print("🎙️ pyttsx3 TTS")
print("=" * 15)
# Get text from command line argument or use default
if len(sys.argv) > 1:
text = " ".join(sys.argv[1:]) # Join all arguments as text
else:
# Default completion messages
completion_messages = [
"Work complete!",
"All done!",
"Task finished!",
"Job complete!",
"Ready for next task!",
]
text = random.choice(completion_messages)
print(f"🎯 Text: {text}")
print("🔊 Speaking...")
# Speak the text
engine.say(text)
engine.runAndWait()
print("✅ Playback complete!")
except ImportError:
print("❌ Error: pyttsx3 package not installed")
print("This script uses UV to auto-install dependencies.")
sys.exit(1)
except Exception as e:
print(f"❌ Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()