Skip to content

Commit

Permalink
add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
shivamp-vg committed Feb 27, 2024
1 parent 12a0871 commit ecf7b50
Showing 1 changed file with 78 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,32 @@
app = Flask(__name__)


# Responses:
new_aivr_session_response = {
"question": {
"text": "This is an echo bot. Say Something..."
}
}


aivr_response = {
"prompt": {
"text": ""
}
}


aivr_disconnect_response = {

"disconnect": {
"reason": "Successfully received feedback",
"prompt": {
"text": "Good Bye!!"
}
}
}


# Define Enum for message types
class MessageTypes(Enum):
PING = "ping"
Expand All @@ -33,8 +59,7 @@ def get_received_msg_type(received_msg):
elif received_msg.get("sid") is not None:
return MessageTypes.NEW_AIVR_SESSION
elif received_msg.get("event") is not None:
if received_msg.get("event").get("type") == "input":
return MessageTypes.AIVR_EVENT
return MessageTypes.AIVR_EVENT
elif received_msg.get("vars") is not None:
return MessageTypes.AIVR_VARS_CHANGED
elif received_msg.get("utt") is not None:
Expand All @@ -46,102 +71,103 @@ def get_received_msg_type(received_msg):
return MessageTypes.NOT_FOUND



# Responses:
new_aivr_session_response = {
"question": {
"text": "This is an echo bot. Say Something..."
}
}


aivr_response = {
"prompt": {
"text": ""
}
}


aivr_disconnect_response = {

"disconnect": {
"reason": "Successfully received feedback",
"prompt": {
"text": "Good Bye!!"
}
}
}



# Function to respond to new AIVR sessions
async def respond_to_new_aivr_session(websocket):
await websocket.send(json.dumps(new_aivr_session_response))



# Function to respond to AIVR events
async def respond_to_aivr_event(websocket, received_msg):
#Echo the same message back
message = received_msg["event"]["vuiAlternatives"][0]["utterance"]
aivr_response["prompt"]["text"] = message
await websocket.send(json.dumps(aivr_response))



# Function to respond to AIVR disconnect events
async def respond_to_aivr_disconnect_event(websocket):
await websocket.send(json.dumps(aivr_disconnect_response))



# Function to run the echo bot
async def run_echo_bot(uri):
async with websockets.connect(uri, write_limit=128, compression=None) as websocket:
while(True):
# Continuously receive messages from the WebSocket
while(True):
print("Receiving message...")

# Receive a message from the WebSocket
received_msg_str = await websocket.recv()

# Parse the received message as JSON
received_msg = json.loads(received_msg_str)

print("Received message: ", received_msg)

# Determine the type of the received message
msg_type = get_received_msg_type(received_msg)


# Check if the received message is a ping
if(msg_type == MessageTypes.PING):
continue

# Check if the received message is a new AIVR session
if(msg_type == MessageTypes.NEW_AIVR_SESSION):
# Respond to the new AIVR session
await respond_to_new_aivr_session(websocket)

# Check if the received message is an AIVR event
if(msg_type == MessageTypes.AIVR_EVENT):
print("Sending the same message back...")
await respond_to_aivr_event(websocket, received_msg)
print("Disconnecting... Goodbye!!")
await respond_to_aivr_disconnect_event(websocket)

# Check if the AIVR event is of type "input", as we have to respond to only input events.
if received_msg.get("event").get("type") == "input":
print("Received an AIVR event of type input, echoing the same message back...")

# Function websocket_flow_main, recv and sends the results over websocket
# Respond to the AIVR event by echoing the same message back
await respond_to_aivr_event(websocket, received_msg)

print("Disconnecting... Goodbye!!")
await respond_to_aivr_disconnect_event(websocket)


# Function to manage WebSocket flow
def websocket_flow_main(uri):
try:
asyncio.run(run_echo_bot(uri))
except Exception as e:
print("Exception caught within websocket_flow_main", e)



# Flask app route to handle POST requests
# Flask app route to handle POST requests.
# This method is called whenever someone calls the telephony bot.
@app.route("/", methods=["POST"])
def post():
global ws_url_final

# Print a message indicating a POST request has been received
print("Post req recieved. ")

# Retrieve the payload from the request
payload = request.json

# Print the payload received in the POST request
print("POST Req!! Payload is: " + str(payload))
# Create a WebSocket connection

try:
# In the first post request, we fetched the wsUrl and began receiving and sending messages.
ws_url_final = payload["wsUrl"]
# Start a thread to call websocket_flow_send_main
# Extract wsUrl from the payload and initiate WebSocket connection
# Start a new thread to call websocket_flow_main function with wsUrl as argument
thread = threading.Thread(target=websocket_flow_main, args=(payload["wsUrl"],))
thread.start()
except Exception as e:
# Print any exception that occurs during WebSocket connection setup
print(e)

# Prepare response data to acknowledge the POST request
data = {"response": "accept"}

# Print a message indicating successful processing of the POST request
print("POST Req returning")

# Return JSON response containing acknowledgment data
return jsonify(data)


Expand All @@ -162,11 +188,14 @@ def delete():
def get():
return "GET req recieved."


# Flask app route for testing
@app.route("/test")
@app.route("/run")
def run():
return "Running test voicegain.ai..."
return "Run test flask server..."


# Main function to run the Flask app
if __name__ == "__main__":
app.run(port=80)

Expand Down

0 comments on commit ecf7b50

Please sign in to comment.