Delete main.py
Browse files
main.py
DELETED
|
@@ -1,215 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import os
|
| 3 |
-
import sys
|
| 4 |
-
import time
|
| 5 |
-
import logging
|
| 6 |
-
from pipecat.frames.frames import (
|
| 7 |
-
TextFrame, UserStartedSpeakingFrame, UserStoppedSpeakingFrame,
|
| 8 |
-
TTSStartedFrame, TTSStoppedFrame
|
| 9 |
-
)
|
| 10 |
-
from pipecat.pipeline.pipeline import Pipeline
|
| 11 |
-
from pipecat.pipeline.runner import PipelineRunner
|
| 12 |
-
from pipecat.pipeline.task import PipelineParams
|
| 13 |
-
from pipecat.processors.frame_processor import FrameProcessor, FrameDirection
|
| 14 |
-
from pipecat.services.elevenlabs import ElevenLabsTTSService
|
| 15 |
-
from pipecat.services.deepgram import DeepgramSTTService
|
| 16 |
-
from pipecat.transports.services.daily import DailyParams, DailyTransport
|
| 17 |
-
from pipecat.vad.silero import SileroVADAnalyzer
|
| 18 |
-
from azure_openai import AzureOpenAILLMService
|
| 19 |
-
from elevenlabs import ElevenLabs
|
| 20 |
-
|
| 21 |
-
# Configure logging
|
| 22 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
| 23 |
-
logger = logging.getLogger(__name__)
|
| 24 |
-
|
| 25 |
-
# Configuration constants
|
| 26 |
-
SILENCE_TIMEOUT_SECONDS = float(os.environ.get("SILENCE_TIMEOUT_SECONDS", 10))
|
| 27 |
-
MAX_SILENCE_PROMPTS = int(os.environ.get("MAX_SILENCE_PROMPTS", 3))
|
| 28 |
-
SILENCE_PROMPT_TEXT = "Are you still there?"
|
| 29 |
-
GOODBYE_PROMPT_TEXT = "It seems you're no longer there. I'm hanging up now. Goodbye."
|
| 30 |
-
|
| 31 |
-
class SilenceAndCallLogicProcessor(FrameProcessor):
|
| 32 |
-
def __init__(self, tts_service, pipeline, app):
|
| 33 |
-
super().__init__()
|
| 34 |
-
self.tts_service = tts_service
|
| 35 |
-
self.pipeline = pipeline
|
| 36 |
-
self.app = app
|
| 37 |
-
self.last_activity_ts = time.time()
|
| 38 |
-
self.silence_prompts_count = 0
|
| 39 |
-
self._bot_is_speaking = False
|
| 40 |
-
self._silence_check_task = None
|
| 41 |
-
self.app.current_call_stats["silence_events"] = 0
|
| 42 |
-
|
| 43 |
-
async def start(self):
|
| 44 |
-
self.last_activity_ts = time.time()
|
| 45 |
-
self.silence_prompts_count = 0
|
| 46 |
-
self._bot_is_speaking = False
|
| 47 |
-
if self._silence_check_task:
|
| 48 |
-
self._silence_check_task.cancel()
|
| 49 |
-
self._silence_check_task = asyncio.create_task(self._check_silence_loop())
|
| 50 |
-
|
| 51 |
-
async def stop(self):
|
| 52 |
-
if self._silence_check_task:
|
| 53 |
-
self._silence_check_task.cancel()
|
| 54 |
-
try:
|
| 55 |
-
await self._silence_check_task
|
| 56 |
-
except asyncio.CancelledError:
|
| 57 |
-
pass
|
| 58 |
-
await self.tts_service.stop()
|
| 59 |
-
|
| 60 |
-
def _reset_activity_timer(self):
|
| 61 |
-
self.last_activity_ts = time.time()
|
| 62 |
-
self.silence_prompts_count = 0
|
| 63 |
-
|
| 64 |
-
async def process_frame(self, frame, direction: FrameDirection):
|
| 65 |
-
if isinstance(frame, (UserStartedSpeakingFrame, TextFrame)) and direction == FrameDirection.UPSTREAM:
|
| 66 |
-
self._reset_activity_timer()
|
| 67 |
-
if isinstance(frame, TTSStartedFrame) and direction == FrameDirection.DOWNSTREAM:
|
| 68 |
-
self._bot_is_speaking = True
|
| 69 |
-
elif isinstance(frame, TTSStoppedFrame) and direction == FrameDirection.DOWNSTREAM:
|
| 70 |
-
self._bot_is_speaking = False
|
| 71 |
-
self.last_activity_ts = time.time()
|
| 72 |
-
await self.push_frame(frame, direction)
|
| 73 |
-
|
| 74 |
-
async def _check_silence_loop(self):
|
| 75 |
-
while True:
|
| 76 |
-
await asyncio.sleep(1)
|
| 77 |
-
if self._bot_is_speaking:
|
| 78 |
-
continue
|
| 79 |
-
if time.time() - self.last_activity_ts > SILENCE_TIMEOUT_SECONDS:
|
| 80 |
-
self.app.current_call_stats["silence_events"] += 1
|
| 81 |
-
self.silence_prompts_count += 1
|
| 82 |
-
self._bot_is_speaking = True
|
| 83 |
-
if self.silence_prompts_count >= MAX_SILENCE_PROMPTS:
|
| 84 |
-
await self.push_frame(TextFrame(GOODBYE_PROMPT_TEXT), FrameDirection.DOWNSTREAM)
|
| 85 |
-
await asyncio.sleep(2)
|
| 86 |
-
await self.pipeline.stop_when_done()
|
| 87 |
-
break
|
| 88 |
-
else:
|
| 89 |
-
await self.push_frame(TextFrame(SILENCE_PROMPT_TEXT), FrameDirection.DOWNSTREAM)
|
| 90 |
-
self.last_activity_ts = time.time()
|
| 91 |
-
self._bot_is_speaking = False
|
| 92 |
-
|
| 93 |
-
class PhoneChatbotApp:
|
| 94 |
-
def __init__(self):
|
| 95 |
-
self.daily_transport = None
|
| 96 |
-
self.pipeline = None
|
| 97 |
-
self.stt_service = None
|
| 98 |
-
self.tts_service = None
|
| 99 |
-
self.llm_service = None
|
| 100 |
-
self.silence_processor = None
|
| 101 |
-
self.call_start_time = None
|
| 102 |
-
self.current_call_stats = {
|
| 103 |
-
"duration_seconds": 0,
|
| 104 |
-
"silence_events": 0,
|
| 105 |
-
"start_time": None,
|
| 106 |
-
"end_time": None,
|
| 107 |
-
"ended_by_silence": False
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
def _reset_call_stats(self):
|
| 111 |
-
self.call_start_time = time.time()
|
| 112 |
-
self.current_call_stats = {
|
| 113 |
-
"duration_seconds": 0,
|
| 114 |
-
"silence_events": 0,
|
| 115 |
-
"start_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.call_start_time)),
|
| 116 |
-
"end_time": None,
|
| 117 |
-
"ended_by_silence": False
|
| 118 |
-
}
|
| 119 |
-
|
| 120 |
-
async def _log_call_summary(self):
|
| 121 |
-
if self.call_start_time:
|
| 122 |
-
call_end_time = time.time()
|
| 123 |
-
self.current_call_stats["duration_seconds"] = round(call_end_time - self.call_start_time, 2)
|
| 124 |
-
self.current_call_stats["end_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(call_end_time))
|
| 125 |
-
if self.silence_processor and self.silence_processor.silence_prompts_count >= MAX_SILENCE_PROMPTS:
|
| 126 |
-
self.current_call_stats["ended_by_silence"] = True
|
| 127 |
-
logger.info("--- Post-Call Summary ---")
|
| 128 |
-
for key, value in self.current_call_stats.items():
|
| 129 |
-
logger.info(f" {key.replace('_', ' ').title()}: {value}")
|
| 130 |
-
logger.info("-------------------------")
|
| 131 |
-
|
| 132 |
-
def setup_pipeline_hook(self, pipeline_params: PipelineParams, room_url: str, token: str):
|
| 133 |
-
self._reset_call_stats()
|
| 134 |
-
self.pipeline = Pipeline([self.stt_service, self.llm_service, self.tts_service])
|
| 135 |
-
self.silence_processor = SilenceAndCallLogicProcessor(
|
| 136 |
-
tts_service=self.tts_service,
|
| 137 |
-
pipeline=self.pipeline,
|
| 138 |
-
app=self
|
| 139 |
-
)
|
| 140 |
-
self.pipeline.processors.append(self.silence_processor)
|
| 141 |
-
pipeline_params.pipeline = self.pipeline
|
| 142 |
-
pipeline_params.params = PipelineParams(allow_interruptions=True, enable_metrics=True)
|
| 143 |
-
return pipeline_params
|
| 144 |
-
|
| 145 |
-
def validate_voice_id(self, voice_id: str) -> bool:
|
| 146 |
-
try:
|
| 147 |
-
client = ElevenLabs(api_key=os.environ.get("elevenlabs"))
|
| 148 |
-
client.voices.get(voice_id=voice_id)
|
| 149 |
-
return True
|
| 150 |
-
except Exception as e:
|
| 151 |
-
logger.error(f"Failed to validate ElevenLabs voice ID {voice_id}: {e}")
|
| 152 |
-
return False
|
| 153 |
-
|
| 154 |
-
async def run(self):
|
| 155 |
-
# Validate environment variables (Hugging Face Secrets)
|
| 156 |
-
required_keys = [
|
| 157 |
-
"deepgram", "elevenlabs", "dailyco", "azure_openai"
|
| 158 |
-
]
|
| 159 |
-
missing_keys = [key for key in required_keys if not os.environ.get(key)]
|
| 160 |
-
if missing_keys:
|
| 161 |
-
logger.error(f"Missing Hugging Face Secrets: {', '.join(missing_keys)}")
|
| 162 |
-
sys.exit(1)
|
| 163 |
-
|
| 164 |
-
# Validate ElevenLabs voice ID
|
| 165 |
-
voice_id = os.environ.get("ELEVENLABS_VOICE_ID", "cgSgspJ2msm6clMCkdW9")
|
| 166 |
-
if not self.validate_voice_id(voice_id):
|
| 167 |
-
logger.error(f"Invalid ElevenLabs voice ID: {voice_id}")
|
| 168 |
-
sys.exit(1)
|
| 169 |
-
|
| 170 |
-
self.stt_service = DeepgramSTTService(
|
| 171 |
-
api_key=os.environ.get("deepgram"),
|
| 172 |
-
input_audio_format="linear16"
|
| 173 |
-
)
|
| 174 |
-
self.tts_service = ElevenLabsTTSService(
|
| 175 |
-
api_key=os.environ.get("elevenlabs"),
|
| 176 |
-
voice_id=voice_id
|
| 177 |
-
)
|
| 178 |
-
self.llm_service = AzureOpenAILLMService(
|
| 179 |
-
preprompt="You are a friendly and helpful phone assistant."
|
| 180 |
-
)
|
| 181 |
-
self.daily_transport = DailyTransport(
|
| 182 |
-
os.environ.get("DAILY_DOMAIN", "your-username.daily.co"),
|
| 183 |
-
os.environ.get("dailyco"),
|
| 184 |
-
None,
|
| 185 |
-
None,
|
| 186 |
-
"Pipecat Phone Demo",
|
| 187 |
-
vad_analyzer=SileroVADAnalyzer(),
|
| 188 |
-
daily_params=DailyParams(
|
| 189 |
-
audio_in_enabled=True,
|
| 190 |
-
audio_out_enabled=True,
|
| 191 |
-
transcription_enabled=False
|
| 192 |
-
)
|
| 193 |
-
)
|
| 194 |
-
self.daily_transport.pipeline_params_hook = self.setup_pipeline_hook
|
| 195 |
-
|
| 196 |
-
runner = PipelineRunner()
|
| 197 |
-
try:
|
| 198 |
-
await runner.run(self.daily_transport)
|
| 199 |
-
except KeyboardInterrupt:
|
| 200 |
-
logger.info("Ctrl+C pressed, shutting down")
|
| 201 |
-
except Exception as e:
|
| 202 |
-
logger.error(f"An error occurred: {e}", exc_info=True)
|
| 203 |
-
finally:
|
| 204 |
-
await self._log_call_summary()
|
| 205 |
-
if self.pipeline:
|
| 206 |
-
await self.pipeline.stop_when_done()
|
| 207 |
-
if self.silence_processor:
|
| 208 |
-
await self.silence_processor.stop()
|
| 209 |
-
|
| 210 |
-
async def main():
|
| 211 |
-
app = PhoneChatbotApp()
|
| 212 |
-
await app.run()
|
| 213 |
-
|
| 214 |
-
if __name__ == "__main__":
|
| 215 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|