removed helps and fixed linting

This commit is contained in:
Jon Taylor
2024-06-06 20:22:35 +02:00
committed by Aleix Conchillo Flaqué
parent de9f3e55f1
commit cc5bfa8af8
3 changed files with 13 additions and 141 deletions

View File

@@ -24,8 +24,8 @@ load_dotenv(override=True)
logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
daily_api_url = os.getenv("DAILY_API_URL", "api.daily.co/v1")
daily_api_key = os.getenv("DAILY_API_KEY")
daily_api_url = os.getenv("DAILY_API_URL", "https://api.daily.co/v1")
daily_api_key = os.getenv("DAILY_API_KEY", "")
async def main(room_url: str, token: str, callId: str, callDomain: str, sipUri: str):
@@ -44,7 +44,7 @@ async def main(room_url: str, token: str, callId: str, callDomain: str, sipUri:
token,
"Chatbot",
DailyParams(
api_url=f"https://{daily_api_url}",
api_url=f"{daily_api_url}",
api_key=daily_api_key,
dialin_settings=diallin_settings,
audio_in_enabled=True,

View File

@@ -2,14 +2,14 @@
bot_runner.py
HTTP service that listens for incoming calls from either Daily or Twilio,
provisioning a room and starting a Pipecat bot in response.
provisioning a room and starting a Pipecat bot in response.
Refer to README for more information.
"""
import os
import argparse
import subprocess
from daily_helpers import DailyRESTHelper, DailyRoomObject, DailyRoomProperties, DailyRoomSipParams, DailyRoomParams
from pipecat.transports.services.helpers.daily_rest import DailyRESTHelper, DailyRoomObject, DailyRoomProperties, DailyRoomSipParams, DailyRoomParams
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, PlainTextResponse
@@ -26,8 +26,8 @@ REQUIRED_ENV_VARS = ['OPENAI_API_KEY', 'DAILY_API_KEY',
'ELEVENLABS_API_KEY', 'ELEVENLABS_VOICE_ID']
daily_rest_helper = DailyRESTHelper(
os.getenv("DAILY_API_KEY", None),
os.getenv("DAILY_API_URL", 'api.daily.co/v1'))
os.getenv("DAILY_API_KEY", ""),
os.getenv("DAILY_API_URL", 'https://api.daily.co/v1'))
# ----------------- API ----------------- #
@@ -48,7 +48,7 @@ When the vendor is Daily, the bot handles the call forwarding automatically,
i.e, forwards the call from the "hold music state" to the Daily Room's SIP URI.
Alternatively, when the vendor is Twilio (not Daily), the bot is responsible for
updating the state on Twilio. So when `dialin-ready` fires, it takes appropriate
updating the state on Twilio. So when `dialin-ready` fires, it takes appropriate
action using the Twilio Client library.
"""
@@ -92,9 +92,11 @@ def _create_daily_room(room_url, callId, callDomain=None, vendor="daily"):
# Spawn a new agent, and join the user session
# Note: this is mostly for demonstration purposes (refer to 'deployment' in docs)
if vendor == "daily":
bot_proc = f"python3 -m bot_daily -u {room.url} -t {token} -i {callId} -d {callDomain} -s {room.config.sip_endpoint}"
bot_proc = f"python3 -m bot_daily -u {room.url} -t {token} -i {
callId} -d {callDomain} -s {room.config.sip_endpoint}"
else:
bot_proc = f"python3 -m bot_twilio -u {room.url} -t {token} -i {callId} -s {room.config.sip_endpoint}"
bot_proc = f"python3 -m bot_twilio -u {room.url} -t {
token} -i {callId} -s {room.config.sip_endpoint}"
try:
subprocess.Popen(
@@ -119,7 +121,7 @@ async def twilio_start_bot(request: Request):
# Click Configure and under Voice Configuration,
# "a call comes in" choose webhook and point the URL to
# where this code is hosted.
data = None
data = {}
try:
# shouldnt have received json, twilio sends form data
form_data = await request.form()

View File

@@ -1,130 +0,0 @@
"""
Daily Helpers
Methods that wrap the Daily API to create rooms, check room URLs, and get meeting tokens.
"""
import urllib.parse
import urllib
import requests
from typing import Literal, Optional
from time import time
from pydantic import BaseModel, ValidationError
class DailyRoomSipParams(BaseModel):
display_name: str = "sw-sip-dialin"
video: bool = False
sip_mode: str = "dial-in"
num_endpoints: int = 1
class DailyRoomProperties(BaseModel):
exp: float = time() + 5 * 60
enable_chat: bool = False
enable_emoji_reactions: bool = False
eject_at_room_exp: bool = True
enable_dialout: Optional[bool] = None
sip: DailyRoomSipParams = None
sip_uri: dict = None
@property
def sip_endpoint(self) -> str:
return "sip:%s" % self.sip_uri['endpoint']
class DailyRoomParams(BaseModel):
name: Optional[str] = None
privacy: Literal['private', 'public'] = "public"
properties: DailyRoomProperties = DailyRoomProperties()
class DailyRoomObject(BaseModel):
id: str
name: str
api_created: bool
privacy: str
url: str
created_at: str
config: DailyRoomProperties
class DailyRESTHelper:
def __init__(self, daily_api_key: str, daily_api_url: str = "api.daily.co/v1"):
self.daily_api_key = daily_api_key
self.daily_api_url = daily_api_url
def _get_name_from_url(self, room_url: str) -> str:
return urllib.parse.urlparse(room_url).path[1:]
def create_room(self, params: DailyRoomParams) -> DailyRoomObject:
res = requests.post(
f"https://{self.daily_api_url}/rooms",
headers={"Authorization": f"Bearer {self.daily_api_key}"},
json={**params.model_dump(exclude_none=True)}
)
if res.status_code != 200:
raise Exception(f"Unable to create room: {res.text}")
data = res.json()
try:
room = DailyRoomObject(**data)
except ValidationError as e:
raise Exception(f"Invalid response: {e}")
return room
def _get_room_from_name(self, room_name: str) -> DailyRoomObject:
res: requests.Response = requests.get(
f"https://{self.daily_api_url}/rooms/{room_name}",
headers={"Authorization": f"Bearer {self.daily_api_key}"}
)
if res.status_code != 200:
raise Exception(f"Room not found: {room_name}")
data = res.json()
try:
room = DailyRoomObject(**data)
except ValidationError as e:
raise Exception(f"Invalid response: {e}")
return room
def get_room_from_url(self, room_url: str,) -> DailyRoomObject:
room_name = self._get_name_from_url(room_url)
return self._get_room_from_name(room_name)
def get_token(self, room_url: str, expiry_time: float = 60 * 60, owner: bool = True) -> str:
if not room_url:
raise Exception(
"No Daily room specified. You must specify a Daily room in order a token to be generated.")
expiration: float = time() + expiry_time
room_name = self._get_name_from_url(room_url)
res: requests.Response = requests.post(
f"https://{self.daily_api_url}/meeting-tokens",
headers={
"Authorization": f"Bearer {self.daily_api_key}"},
json={
"properties": {
"room_name": room_name,
"is_owner": owner,
"exp": expiration
}},
)
if res.status_code != 200:
raise Exception(
f"Failed to create meeting token: {res.status_code} {res.text}")
token: str = res.json()["token"]
return token