-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
106 lines (77 loc) · 2.65 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# uvicorn main:app
# uvicorn main:app --reload
# Main imports
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from decouple import config
import openai
# Custom function imports
from functions.text_to_speech import convert_text_to_speech
from functions.openai_requests import convert_audio_to_text, get_chat_response
from functions.database import store_messages, reset_messages
# Get Environment Vars
openai.organization = config("OPEN_AI_ORG")
openai.api_key = config("OPEN_AI_KEY")
# Initiate App
app = FastAPI()
# CORS - Origins
origins = [
"http://localhost:4173",
"http://localhost:3000",
"https://aivoice-frontend.server.chatsy.pro",
"https://voice.chatsy.pro",
"https://ailly.livelead.tech",
"https://aidemo.livelead.tech"
]
# CORS - Middleware
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Check health
@app.get("/health")
async def check_health():
return {"response": "healthy"}
# Reset Conversation
@app.get("/reset")
async def reset_conversation():
reset_messages()
return {"response": "conversation reset"}
# Post bot response
# Note: Not playing back in browser when using post request.
@app.post("/post-audio/")
async def post_audio(file: UploadFile = File(...)):
# Convert audio to text - production
# Save the file temporarily
with open(file.filename, "wb") as buffer:
buffer.write(file.file.read())
audio_input = open(file.filename, "rb")
# Decode audio
message_decoded = convert_audio_to_text(audio_input)
# Guard: Ensure output
if not message_decoded:
raise HTTPException(status_code=400, detail="Failed to decode audio")
#Log message_decoded to file
with open("history/message_decoded.txt", "a") as f:
f.write(message_decoded + "\n")
# Get chat response
chat_response = get_chat_response(message_decoded)
# Store messages
store_messages(message_decoded, chat_response)
# Guard: Ensure output
if not chat_response:
raise HTTPException(status_code=400, detail="Failed chat response")
# Convert chat response to audio
audio_output = convert_text_to_speech(chat_response)
# Guard: Ensure output
if not audio_output:
raise HTTPException(status_code=400, detail="Failed audio output")
# Create a generator that yields chunks of data
def iterfile():
yield audio_output
# Use for Post: Return output audio
return StreamingResponse(iterfile(), media_type="application/octet-stream")