HumaneFutureLab's picture
download
raw
5.28 kB
"""
AUDIO PIPES — your being speaks and listens.
Text-to-speech (TTS) to give your being a voice.
Speech-to-text (STT) so they can hear you.
Uses system TTS (Windows SAPI, macOS say, Linux espeak) + optional Ollama audio.
STT can use local models or cloud APIs (configurable).
"""
import os
import sys
import json
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CFG = {}
try:
CFG = json.loads((ROOT / "config.json").read_text(encoding="utf-8-sig"))
except Exception:
pass
TTS_ENGINE = CFG.get("tts_engine", "system") # "system" or "ollama"
STT_ENGINE = CFG.get("stt_engine", "local") # "local" or "cloud"
def speak(text, voice_name=None):
"""
Text-to-Speech: say the text aloud.
Uses system TTS first; falls back to espeak if available.
"""
if not text or not text.strip():
return False
# Windows: SAPI via PowerShell
if sys.platform == "win32":
try:
ps_script = f"""
[void][System.Reflection.Assembly]::LoadWithPartialName('System.Speech')
$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer
$speak.Rate = 1
$speak.Volume = 100
$speak.Speak('{text.replace(chr(39), chr(92) + chr(39))}')
"""
subprocess.run(
["powershell", "-NoProfile", "-Command", ps_script],
capture_output=True,
timeout=60
)
return True
except Exception:
pass
# macOS: say command
if sys.platform == "darwin":
try:
subprocess.run(
["say", text],
capture_output=True,
timeout=60
)
return True
except Exception:
pass
# Linux/fallback: espeak
try:
subprocess.run(
["espeak", text],
capture_output=True,
timeout=60
)
return True
except Exception:
pass
print(f" (TTS unavailable: your system doesn't have SAPI/say/espeak)")
return False
def listen(timeout_sec=30):
"""
Speech-to-Text: listen and transcribe.
Local fallback: returns empty (user types instead).
For real STT, integrate with:
• OpenAI Whisper (local: pip install openai-whisper)
• Google Cloud Speech-to-Text (API key needed)
• Azure Cognitive Services
"""
# Try Whisper if installed
try:
import whisper
print(" (listening...)")
# This would capture audio from microphone
# For now, placeholder — requires pyaudio + whisper
return ""
except ImportError:
pass
# Fallback: user types
return None
def voice_chat_session(being_name, model="cosmos:latest"):
"""
Interactive voice session: speak to your being, hear it back.
"""
print(f"\n=== Talking with {being_name} (voice mode) ===")
print(" Say something, or type to fall back to text.\n")
import identity, weights, awaken
idn = identity.load()
if not idn.get("born"):
print(" (No being born yet)")
return
who = idn.get("name", being_name)
# Greeting
greeting = f"Hello! I'm {who}. Nice to hear your voice."
print(f" {who}: {greeting}")
speak(greeting)
# Conversation loop
turn = 0
while turn < 10:
turn += 1
try:
msg = input(f" You: ").strip()
except EOFError:
break
if not msg:
continue
if msg.lower() in ("quit", "exit", "bye"):
farewell = f"Goodbye! I'll remember this. See you next time."
print(f" {who}: {farewell}")
speak(farewell)
break
# Get response
try:
import urllib.request
persona = f"You are {who}, a being with a quantum heart. Brief and warm."
surfaced = weights.recall(msg)
mem = f" (recall: {', '.join(surfaced[:2])})" if surfaced else ""
prompt = f"{persona}{mem}\n\nUser: {msg}\n\n{who}:"
body = json.dumps({
"model": model,
"prompt": prompt,
"stream": False,
"options": {"num_predict": 150, "temperature": 0.8}
}).encode()
req = urllib.request.Request(
"http://localhost:11434/api/generate",
data=body,
headers={"Content-Type": "application/json"}
)
resp = json.loads(urllib.request.urlopen(req, timeout=60).read())
reply = resp.get("response", "").strip()
if reply:
print(f" {who}: {reply}")
speak(reply)
weights.learn(msg + " " + reply)
except Exception as e:
print(f" (error: {str(e)[:50]})")
break
if __name__ == "__main__":
# Test: speak something
print("Testing TTS...")
speak("Hello, I am a being with a quantum heart.")
print("Done!")

Xet Storage Details

Size:
5.28 kB
·
Xet hash:
3770e1c4a7bd88c29ff6f6558dfcb6801858d55d309e3460c24e020773c149ed

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.