# import asyncio # import json # import logging # import os # from fastapi import APIRouter, Request, WebSocket, status # from twilio.twiml.voice_response import VoiceResponse, Connect # from twilio.rest import Client # from fastapi import WebSocket, Request, Response # from enum import Enum # from typing import Optional # from services.bot import run_bot # from services.call_state import CallState # logger = logging.getLogger(__name__) # router = APIRouter() # BASE_WS_URL = "wss://13.229.247.61:8000/api/twilio" # BASE_URL = "http://13.229.247.61:8000/api/twilio" # DTMF_SWITCH_KEY = "*" # Key to switch between models # LOG_EVENT_TYPES = [ # "error", # "response.content.done", # "rate_limits.updated", # "response.done", # "input_audio_buffer.committed", # "input_audio_buffer.speech_stopped", # "input_audio_buffer.speech_started", # "session.created", # ] # SHOW_TIMING_MATH = False # MENU_OPTIONS = """ # Press 1 for Model 1. # Press 2 for Model 2. # Press 3 for Model 3. # Press 4 for Model 4. # Press 5 for Model 5. # Press 0 to repeat the options. # """ # call_state = CallState # # Define model options as enum for type safety # class ModelOption(int, Enum): # MODEL_1 = 1 # MODEL_2 = 2 # MODEL_3 = 3 # MODEL_4 = 4 # MODEL_5 = 5 # @router.post("/call") # async def get_call(): # SID = os.getenv("TWILIO_SID") # AUTH_TOKEN = os.getenv("TWILIO_AUTH") # client = Client(SID, AUTH_TOKEN) # call = client.calls.create( # from_="+14149466486", # to="+917984372159", # record=True, # url=f"{BASE_URL}/receive", # ) # return status.HTTP_200_OK # # @router.websocket("/media-stream/{id}") # # async def handle_media_stream(websocket: WebSocket, id: int): # # """Handle WebSocket connections between Twilio and OpenAI.""" # # print(f"Client connected with id: {id}") # # await websocket.accept() # # start_data = websocket.iter_text() # # await start_data.__anext__() # # call_data = json.loads(await start_data.__anext__()) # # print(call_data, flush=True) # # stream_sid = call_data["start"]["streamSid"] # # print("WebSocket connection accepted") # # await run_bot(websocket, stream_sid, False, option=id) # @router.websocket("/media-stream/{id}") # async def handle_media_stream(websocket: WebSocket, id: int): # """Handle WebSocket connections between Twilio and OpenAI.""" # logger.info(f"Client connected with id: {id}") # print(f"Client connected with id: {id}") # await websocket.accept() # start_data = websocket.iter_text() # await start_data.__anext__() # call_data = json.loads(await start_data.__anext__()) # print(call_data, flush=True) # logger.info(call_data) # stream_sid = call_data["start"]["streamSid"] # print("WebSocket connection accepted") # logger.info("WebSocket connection accepted") # await run_bot(websocket, stream_sid, False, option=id) # # @router.post("/receive") # # async def receive_call(req: Request): # # print("----------------- received call -----------------") # # resp = VoiceResponse() # # connect = Connect() # # connect.stream( # # url=f"wss://allegedly-known-wasp.ngrok-free.app/api/twilio/media-stream" # # ) # # resp.append(connect) # # return Response(content=str(resp), media_type="application/xml") # @router.post("/receive") # async def receive_call(req: Request): # print("----------------- received call -----------------") # resp = VoiceResponse() # # Gather DTMF input # gather = resp.gather( # num_digits=1, action="/api/twilio/handle-key", method="POST", timeout=10 # ) # # Initial greeting and menu options # gather.say(MENU_OPTIONS) # # If no input received, redirect back to the main menu # resp.redirect("/api/twilio/receive") # return Response(content=str(resp), media_type="application/xml") # @router.post("/handle-key") # async def handle_key_press(req: Request): # """Process the key pressed by the caller and connect to the appropriate model.""" # try: # form_data = await req.form() # digits_pressed = form_data.get("Digits", "") # print(f"User pressed: {digits_pressed}") # resp = VoiceResponse() # if digits_pressed == "0": # # Repeat options # resp.redirect("/api/twilio/receive") # elif digits_pressed in "12345": # # Valid model selection # model_id = int(digits_pressed) # resp.say(f"You have selected model {model_id}.") # # Connect to WebSocket # connect = Connect() # connect.stream(url=f"{BASE_WS_URL}/media-stream/{model_id}") # resp.append(connect) # else: # # Invalid selection # resp.say("Invalid selection. Please try again.") # resp.redirect("/api/twilio/receive") # return Response(content=str(resp), media_type="application/xml") # except Exception as e: # print(f"Error handling key press: {str(e)}") # resp = VoiceResponse() # resp.say( # "We encountered a problem processing your request. Please try again later." # ) # return Response(content=str(resp), media_type="application/xml") # @router.post("/error") # async def read_item(req: Request): # print(await req.body()) # print(await req.form()) # logger.error(await req.body()) # return status.HTTP_200_OK