Spaces:
Runtime error
Runtime error
peacepeacecreation commited on
Commit Β·
a2b0d2f
1
Parent(s): 77b4a42
Add local/ module
Browse files- Dockerfile +1 -0
- local/__init__.py +0 -0
- local/__pycache__/__init__.cpython-313.pyc +0 -0
- local/__pycache__/recording.cpython-313.pyc +0 -0
- local/__pycache__/runner.cpython-313.pyc +0 -0
- local/__pycache__/server.cpython-313.pyc +0 -0
- local/recording.py +127 -0
- local/runner.py +113 -0
- local/server.py +244 -0
Dockerfile
CHANGED
|
@@ -30,6 +30,7 @@ COPY --chown=user:user core/ ./core/
|
|
| 30 |
COPY --chown=user:user utils/ ./utils/
|
| 31 |
COPY --chown=user:user metrics/ ./metrics/
|
| 32 |
COPY --chown=user:user livekit_server/ ./livekit_server/
|
|
|
|
| 33 |
|
| 34 |
# Install dependencies (frozen to use lockfile)
|
| 35 |
RUN $HOME/.local/bin/uv sync --frozen --no-dev
|
|
|
|
| 30 |
COPY --chown=user:user utils/ ./utils/
|
| 31 |
COPY --chown=user:user metrics/ ./metrics/
|
| 32 |
COPY --chown=user:user livekit_server/ ./livekit_server/
|
| 33 |
+
COPY --chown=user:user local/ ./local/
|
| 34 |
|
| 35 |
# Install dependencies (frozen to use lockfile)
|
| 36 |
RUN $HOME/.local/bin/uv sync --frozen --no-dev
|
local/__init__.py
ADDED
|
File without changes
|
local/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (165 Bytes). View file
|
|
|
local/__pycache__/recording.cpython-313.pyc
ADDED
|
Binary file (6.26 kB). View file
|
|
|
local/__pycache__/runner.cpython-313.pyc
ADDED
|
Binary file (5.68 kB). View file
|
|
|
local/__pycache__/server.cpython-313.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
local/recording.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Local recording functionality for Casey test compatibility.
|
| 3 |
+
Provides audio recording to local files instead of S3.
|
| 4 |
+
Based on the working implementation from casey/python-scripts/stacy/recording_utils.py
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import io
|
| 8 |
+
import wave
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Optional
|
| 12 |
+
from loguru import logger
|
| 13 |
+
|
| 14 |
+
from pipecat.processors.audio.audio_buffer_processor import AudioBufferProcessor
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class AudioRecordingHandler:
|
| 18 |
+
"""Handles audio recording and saves files to tmp directory.
|
| 19 |
+
|
| 20 |
+
Records both merged conversation audio and separate user/bot tracks.
|
| 21 |
+
Based on casey/python-scripts/stacy implementation.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, session_id: Optional[str] = None, tmp_dir: str = "/tmp"):
|
| 25 |
+
"""Initialize audio recording handler.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
session_id: Unique identifier for the session. If None, uses timestamp.
|
| 29 |
+
tmp_dir: Directory to save audio files. Defaults to /tmp.
|
| 30 |
+
"""
|
| 31 |
+
self.session_id = session_id or datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 32 |
+
self.tmp_dir = Path(tmp_dir)
|
| 33 |
+
self.tmp_dir.mkdir(exist_ok=True)
|
| 34 |
+
|
| 35 |
+
logger.info(
|
| 36 |
+
f"π Audio recording handler initialized for session {self.session_id}"
|
| 37 |
+
)
|
| 38 |
+
logger.info(f"π Audio files will be saved to: {self.tmp_dir}")
|
| 39 |
+
|
| 40 |
+
async def save_audio_file(
|
| 41 |
+
self, audio: bytes, filename: str, sample_rate: int, num_channels: int
|
| 42 |
+
):
|
| 43 |
+
"""Save audio data to a WAV file.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
audio: Raw audio data
|
| 47 |
+
filename: Output filename
|
| 48 |
+
sample_rate: Audio sample rate
|
| 49 |
+
num_channels: Number of audio channels
|
| 50 |
+
"""
|
| 51 |
+
if len(audio) > 0:
|
| 52 |
+
full_path = self.tmp_dir / filename
|
| 53 |
+
|
| 54 |
+
with io.BytesIO() as buffer:
|
| 55 |
+
with wave.open(buffer, "wb") as wf:
|
| 56 |
+
wf.setsampwidth(2) # 16-bit audio
|
| 57 |
+
wf.setnchannels(num_channels)
|
| 58 |
+
wf.setframerate(sample_rate)
|
| 59 |
+
wf.writeframes(audio)
|
| 60 |
+
|
| 61 |
+
with open(full_path, "wb") as file:
|
| 62 |
+
file.write(buffer.getvalue())
|
| 63 |
+
|
| 64 |
+
logger.info(f"πΎ Audio saved to {full_path}")
|
| 65 |
+
|
| 66 |
+
async def on_audio_data(self, buffer, audio, sample_rate, num_channels):
|
| 67 |
+
"""Handler for merged audio data.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
buffer: AudioBufferProcessor instance
|
| 71 |
+
audio: Combined audio data
|
| 72 |
+
sample_rate: Audio sample rate
|
| 73 |
+
num_channels: Number of channels
|
| 74 |
+
"""
|
| 75 |
+
filename = f"conversation_{self.session_id}.wav"
|
| 76 |
+
await self.save_audio_file(audio, filename, sample_rate, num_channels)
|
| 77 |
+
|
| 78 |
+
async def on_track_audio_data(
|
| 79 |
+
self, buffer, user_audio, bot_audio, sample_rate, num_channels
|
| 80 |
+
):
|
| 81 |
+
"""Handler for separate track audio data.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
buffer: AudioBufferProcessor instance
|
| 85 |
+
user_audio: User audio data
|
| 86 |
+
bot_audio: Bot audio data
|
| 87 |
+
sample_rate: Audio sample rate
|
| 88 |
+
num_channels: Number of channels (per track)
|
| 89 |
+
"""
|
| 90 |
+
# Save user audio
|
| 91 |
+
user_filename = f"user_{self.session_id}.wav"
|
| 92 |
+
await self.save_audio_file(user_audio, user_filename, sample_rate, 1)
|
| 93 |
+
|
| 94 |
+
# Save bot audio
|
| 95 |
+
bot_filename = f"bot_{self.session_id}.wav"
|
| 96 |
+
await self.save_audio_file(bot_audio, bot_filename, sample_rate, 1)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def create_recording_processors(
|
| 100 |
+
session_id: Optional[str] = None, tmp_dir: str = "/tmp"
|
| 101 |
+
):
|
| 102 |
+
"""Create transcript processor and audio buffer processor with handlers.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
session_id: Unique identifier for the session
|
| 106 |
+
tmp_dir: Directory to save files
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
Tuple of (transcript_processor, audio_buffer_processor, handlers)
|
| 110 |
+
"""
|
| 111 |
+
# Create handlers
|
| 112 |
+
audio_handler = AudioRecordingHandler(session_id, tmp_dir)
|
| 113 |
+
audio_buffer_processor = AudioBufferProcessor()
|
| 114 |
+
|
| 115 |
+
@audio_buffer_processor.event_handler("on_audio_data")
|
| 116 |
+
async def on_audio_data(buffer, audio, sample_rate, num_channels):
|
| 117 |
+
await audio_handler.on_audio_data(buffer, audio, sample_rate, num_channels)
|
| 118 |
+
|
| 119 |
+
@audio_buffer_processor.event_handler("on_track_audio_data")
|
| 120 |
+
async def on_track_audio_data(
|
| 121 |
+
buffer, user_audio, bot_audio, sample_rate, num_channels
|
| 122 |
+
):
|
| 123 |
+
await audio_handler.on_track_audio_data(
|
| 124 |
+
buffer, user_audio, bot_audio, sample_rate, num_channels
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
return audio_buffer_processor
|
local/runner.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Bot runner for local development.
|
| 3 |
+
|
| 4 |
+
This script is called as a subprocess by the local FastAPI server.
|
| 5 |
+
It reads configuration from command line arguments and starts the bot.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import asyncio
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
from loguru import logger
|
| 14 |
+
|
| 15 |
+
# Add parent directory (project root) to Python path for imports
|
| 16 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 17 |
+
|
| 18 |
+
from bot_config import BotConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def parse_args():
|
| 22 |
+
"""Parse command line arguments."""
|
| 23 |
+
parser = argparse.ArgumentParser(description="Pipecat bot runner")
|
| 24 |
+
parser.add_argument("--session-id", required=True, help="Session ID for the bot")
|
| 25 |
+
parser.add_argument("--room-url", required=True, help="Daily room URL")
|
| 26 |
+
parser.add_argument("--token", required=True, help="Daily room token")
|
| 27 |
+
|
| 28 |
+
# Bot data can be provided as JSON string or file
|
| 29 |
+
bot_data_group = parser.add_mutually_exclusive_group(required=True)
|
| 30 |
+
bot_data_group.add_argument("--bot-data", help="JSON bot configuration data")
|
| 31 |
+
bot_data_group.add_argument(
|
| 32 |
+
"--bot-config-file", help="Path to JSON bot configuration file"
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
parser.add_argument("--bot-name", default="bot", help="Bot name")
|
| 36 |
+
parser.add_argument("--recording-dir", default="/tmp", help="Recording directory")
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--local-recording", action="store_true", help="Enable local recording"
|
| 39 |
+
)
|
| 40 |
+
parser.add_argument(
|
| 41 |
+
"--disable-rtvi",
|
| 42 |
+
action="store_true",
|
| 43 |
+
help="Disable RTVI processor and observer",
|
| 44 |
+
)
|
| 45 |
+
return parser.parse_args()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
async def main():
|
| 49 |
+
"""Main entry point for the bot runner."""
|
| 50 |
+
try:
|
| 51 |
+
# Parse command line arguments
|
| 52 |
+
args = parse_args()
|
| 53 |
+
|
| 54 |
+
# Parse and validate bot data
|
| 55 |
+
try:
|
| 56 |
+
if args.bot_data:
|
| 57 |
+
raw_bot_data = json.loads(args.bot_data)
|
| 58 |
+
elif args.bot_config_file:
|
| 59 |
+
with open(args.bot_config_file, "r") as f:
|
| 60 |
+
raw_bot_data = json.load(f)
|
| 61 |
+
logger.info(f"π Loaded bot config from file: {args.bot_config_file}")
|
| 62 |
+
else:
|
| 63 |
+
logger.error("β No bot data provided")
|
| 64 |
+
sys.exit(1)
|
| 65 |
+
except FileNotFoundError as e:
|
| 66 |
+
logger.error(f"β Bot config file not found: {e}")
|
| 67 |
+
sys.exit(1)
|
| 68 |
+
except json.JSONDecodeError as e:
|
| 69 |
+
logger.error(f"β Failed to parse bot data JSON: {e}")
|
| 70 |
+
sys.exit(1)
|
| 71 |
+
except ValueError as e:
|
| 72 |
+
logger.error(f"β Invalid bot data format: {e}")
|
| 73 |
+
sys.exit(1)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"β Failed to validate bot data: {e}")
|
| 76 |
+
sys.exit(1)
|
| 77 |
+
|
| 78 |
+
# Create bot config
|
| 79 |
+
config = BotConfig(
|
| 80 |
+
session_id=args.session_id,
|
| 81 |
+
room_url=args.room_url,
|
| 82 |
+
token=args.token,
|
| 83 |
+
bot_data=raw_bot_data,
|
| 84 |
+
bot_name=args.bot_name,
|
| 85 |
+
recording_dir=args.recording_dir,
|
| 86 |
+
local_recording=args.local_recording,
|
| 87 |
+
rtvi_enabled=not args.disable_rtvi,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
logger.info(f"π€ Starting bot runner for session: {config.session_id}")
|
| 91 |
+
logger.info(f"π Room URL: {config.room_url}")
|
| 92 |
+
logger.info(f"π Bot name: {config.bot_name}")
|
| 93 |
+
|
| 94 |
+
# Import and run the bot
|
| 95 |
+
from bot import main as bot_main
|
| 96 |
+
|
| 97 |
+
await bot_main(config)
|
| 98 |
+
|
| 99 |
+
except KeyboardInterrupt:
|
| 100 |
+
logger.info("π Bot runner interrupted by user")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__ == "__main__":
|
| 104 |
+
# Configure logging
|
| 105 |
+
logger.remove() # Remove default handler
|
| 106 |
+
logger.add(
|
| 107 |
+
sys.stdout,
|
| 108 |
+
format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>bot</cyan> | <level>{message}</level>",
|
| 109 |
+
level="INFO",
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# Run the bot
|
| 113 |
+
asyncio.run(main())
|
local/server.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Local FastAPI server for Pipecat development.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import uuid
|
| 11 |
+
import time
|
| 12 |
+
from typing import Dict, Any, Optional
|
| 13 |
+
|
| 14 |
+
import aiohttp
|
| 15 |
+
from fastapi import FastAPI, HTTPException, WebSocket
|
| 16 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
+
from pydantic import BaseModel
|
| 18 |
+
import uvicorn
|
| 19 |
+
from loguru import logger
|
| 20 |
+
from dotenv import load_dotenv
|
| 21 |
+
|
| 22 |
+
# Add parent directory for imports
|
| 23 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 24 |
+
from utils.session import get_max_session_duration
|
| 25 |
+
|
| 26 |
+
from pipecat.transports.daily.utils import (
|
| 27 |
+
DailyRESTHelper,
|
| 28 |
+
DailyRoomParams,
|
| 29 |
+
DailyRoomProperties,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Load environment variables
|
| 33 |
+
load_dotenv()
|
| 34 |
+
|
| 35 |
+
app = FastAPI(title="Local Pipecat Server", version="1.0.0")
|
| 36 |
+
|
| 37 |
+
# Add CORS middleware
|
| 38 |
+
app.add_middleware(
|
| 39 |
+
CORSMiddleware,
|
| 40 |
+
allow_origins=["*"],
|
| 41 |
+
allow_credentials=True,
|
| 42 |
+
allow_methods=["*"],
|
| 43 |
+
allow_headers=["*"],
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class BotStartRequest(BaseModel):
|
| 48 |
+
createDailyRoom: bool = True
|
| 49 |
+
dailyRoomProperties: Optional[Dict[str, Any]] = None
|
| 50 |
+
body: Dict[str, Any]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class BotStartResponse(BaseModel):
|
| 54 |
+
dailyRoom: str
|
| 55 |
+
dailyToken: str
|
| 56 |
+
session_id: Optional[str] = None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@app.post("/", response_model=BotStartResponse)
|
| 60 |
+
async def start_bot(request: BotStartRequest):
|
| 61 |
+
"""Start a bot process locally."""
|
| 62 |
+
try:
|
| 63 |
+
session_id = str(uuid.uuid4())
|
| 64 |
+
|
| 65 |
+
logger.info(f"π Starting bot session: {session_id}")
|
| 66 |
+
|
| 67 |
+
# Get max session duration with priority: API > ENV > Default
|
| 68 |
+
max_session_duration = get_max_session_duration(request.body)
|
| 69 |
+
|
| 70 |
+
# Add max_session_duration to bot_data if not already present
|
| 71 |
+
bot_data = request.body.copy()
|
| 72 |
+
if "max_session_duration" not in bot_data:
|
| 73 |
+
bot_data["max_session_duration"] = max_session_duration
|
| 74 |
+
|
| 75 |
+
# Create Daily room and token
|
| 76 |
+
room_url, token = await create_daily_room_and_token(session_id, request)
|
| 77 |
+
|
| 78 |
+
# Start bot process with piped logs
|
| 79 |
+
await start_bot_process(session_id, room_url, token, bot_data)
|
| 80 |
+
|
| 81 |
+
logger.info(f"β
Bot started successfully for session: {session_id}")
|
| 82 |
+
|
| 83 |
+
return BotStartResponse(
|
| 84 |
+
dailyRoom=room_url, dailyToken=token, session_id=session_id
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
logger.error(f"β Error starting bot: {e}")
|
| 89 |
+
raise HTTPException(status_code=500, detail=f"Failed to start bot: {str(e)}")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
async def create_daily_room_and_token(
|
| 93 |
+
session_id: str, request: BotStartRequest
|
| 94 |
+
) -> tuple[str, str]:
|
| 95 |
+
"""Create a Daily room and meeting token."""
|
| 96 |
+
daily_api_key = os.getenv("DAILY_API_KEY")
|
| 97 |
+
if not daily_api_key:
|
| 98 |
+
raise HTTPException(
|
| 99 |
+
status_code=500, detail="DAILY_API_KEY environment variable is required"
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Get max session duration with priority: API > ENV > Default
|
| 103 |
+
max_session_duration = get_max_session_duration(request.body)
|
| 104 |
+
|
| 105 |
+
async with aiohttp.ClientSession() as http_session:
|
| 106 |
+
daily_helper = DailyRESTHelper(
|
| 107 |
+
daily_api_key=daily_api_key, aiohttp_session=http_session
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
enable_recording = None
|
| 111 |
+
recordings_bucket = None
|
| 112 |
+
recordings_template = None
|
| 113 |
+
if request.dailyRoomProperties:
|
| 114 |
+
enable_recording = request.dailyRoomProperties.get(
|
| 115 |
+
"enable_recording", False
|
| 116 |
+
)
|
| 117 |
+
recordings_bucket = request.dailyRoomProperties.get(
|
| 118 |
+
"recordings_bucket", None
|
| 119 |
+
)
|
| 120 |
+
recordings_template = request.dailyRoomProperties.get(
|
| 121 |
+
"recordings_template", None
|
| 122 |
+
).replace(" ", "_")
|
| 123 |
+
|
| 124 |
+
room_properties = DailyRoomProperties(
|
| 125 |
+
exp=int(time.time() + max_session_duration),
|
| 126 |
+
enable_chat=False,
|
| 127 |
+
enable_prejoin_ui=False,
|
| 128 |
+
start_video_off=True,
|
| 129 |
+
eject_at_room_exp=True,
|
| 130 |
+
enable_recording=enable_recording,
|
| 131 |
+
recordings_bucket=recordings_bucket,
|
| 132 |
+
recordings_template=recordings_template, # type: ignore[attr-defined]
|
| 133 |
+
dialout_config={"max_idle_timeout_sec": 0},
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
room_name = f"pipecat-local-{session_id[:8]}"
|
| 137 |
+
room_params = DailyRoomParams(
|
| 138 |
+
name=room_name, privacy="public", properties=room_properties
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
logger.info(f"π Creating Daily room: {room_name}")
|
| 142 |
+
room = await daily_helper.create_room(room_params)
|
| 143 |
+
|
| 144 |
+
logger.info(f"π« Creating meeting token for room: {room.name}")
|
| 145 |
+
token = await daily_helper.get_token(
|
| 146 |
+
room_url=room.url, expiry_time=3600, eject_at_token_exp=True, owner=True
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
logger.info(f"β
Daily room created: {room.url}")
|
| 150 |
+
return room.url, token
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
async def start_bot_process(
|
| 154 |
+
session_id: str, room_url: str, token: str, bot_data: Dict[str, Any]
|
| 155 |
+
):
|
| 156 |
+
"""Start the bot.py process with piped stdout/stderr."""
|
| 157 |
+
try:
|
| 158 |
+
# Get project root (parent of local/)
|
| 159 |
+
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 160 |
+
|
| 161 |
+
cmd = [
|
| 162 |
+
"uv",
|
| 163 |
+
"run",
|
| 164 |
+
"local/runner.py",
|
| 165 |
+
"--session-id",
|
| 166 |
+
session_id,
|
| 167 |
+
"--room-url",
|
| 168 |
+
room_url,
|
| 169 |
+
"--token",
|
| 170 |
+
token,
|
| 171 |
+
"--bot-data",
|
| 172 |
+
json.dumps(bot_data),
|
| 173 |
+
]
|
| 174 |
+
|
| 175 |
+
logger.info(f"π§ Starting bot process in {project_root}")
|
| 176 |
+
logger.info(f"π§ Command: {' '.join(cmd)}")
|
| 177 |
+
|
| 178 |
+
# Start process with logs piped to this process
|
| 179 |
+
process = subprocess.Popen(
|
| 180 |
+
cmd,
|
| 181 |
+
cwd=project_root,
|
| 182 |
+
env=os.environ.copy(),
|
| 183 |
+
stdout=subprocess.PIPE,
|
| 184 |
+
stderr=subprocess.STDOUT, # Merge stderr into stdout
|
| 185 |
+
text=True,
|
| 186 |
+
bufsize=1,
|
| 187 |
+
universal_newlines=True,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
logger.info(f"β
Bot process started with PID: {process.pid}")
|
| 191 |
+
|
| 192 |
+
# Start task to pipe logs
|
| 193 |
+
asyncio.create_task(pipe_logs(process, session_id))
|
| 194 |
+
|
| 195 |
+
except Exception as e:
|
| 196 |
+
logger.error(f"β Failed to start bot process: {e}")
|
| 197 |
+
raise
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
async def pipe_logs(process: subprocess.Popen, session_id: str):
|
| 201 |
+
"""Pipe subprocess logs to main logger."""
|
| 202 |
+
try:
|
| 203 |
+
while True:
|
| 204 |
+
line = process.stdout.readline()
|
| 205 |
+
if not line:
|
| 206 |
+
if process.poll() is not None:
|
| 207 |
+
break
|
| 208 |
+
await asyncio.sleep(0.1)
|
| 209 |
+
continue
|
| 210 |
+
|
| 211 |
+
# Log subprocess output with session prefix
|
| 212 |
+
logger.info(f"[{session_id[:8]}] {line.strip()}")
|
| 213 |
+
|
| 214 |
+
except Exception as e:
|
| 215 |
+
logger.error(f"β Error piping logs for {session_id}: {e}")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# Twilio WebSocket endpoint for Media Streams
|
| 219 |
+
@app.websocket("/twilio")
|
| 220 |
+
async def twilio_websocket(websocket: WebSocket):
|
| 221 |
+
"""
|
| 222 |
+
Twilio Media Streams WebSocket endpoint.
|
| 223 |
+
|
| 224 |
+
This handles incoming calls via Twilio's <Stream> TwiML directive.
|
| 225 |
+
"""
|
| 226 |
+
try:
|
| 227 |
+
from bot import twilio_websocket_handler
|
| 228 |
+
await twilio_websocket_handler(websocket)
|
| 229 |
+
except ImportError as e:
|
| 230 |
+
logger.error(f"β Failed to import bot: {e}")
|
| 231 |
+
await websocket.close(code=1011, reason="Server configuration error")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
host = "127.0.0.1"
|
| 236 |
+
port = 8000
|
| 237 |
+
|
| 238 |
+
logger.info("π Starting Local Pipecat Server")
|
| 239 |
+
logger.info(f"π Server will run at: http://{host}:{port}")
|
| 240 |
+
logger.info("π Available endpoints:")
|
| 241 |
+
logger.info(" POST / - Start bot session (Daily.co/WebRTC)")
|
| 242 |
+
logger.info(" WS /twilio - Twilio Media Streams WebSocket")
|
| 243 |
+
|
| 244 |
+
uvicorn.run(app, host=host, port=port, log_level="info")
|