File size: 8,526 Bytes
18092b2 3b4968e b64bb23 3b4968e 7db8704 b64bb23 630fe1c 3b4968e c88bfae 3b4968e b64bb23 1b4cab5 3ba759c 39d90db b64bb23 3b4968e 5dda573 3b4968e c5a6d28 7db8704 3b4968e 7db8704 3b4968e bf48613 09351a6 3b4968e 09351a6 39d90db bf48613 39d90db 09351a6 |
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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
from fastapi import FastAPI, UploadFile, File, Response, Request, Form, Body
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import ggwave
import scipy.io.wavfile as wav
import numpy as np
import os
from pydantic import BaseModel
from groq import Groq
import io
import wave
import json
from typing import List, Dict, Optional
app = FastAPI()
# Serve static files
app.mount("/static", StaticFiles(directory="static"), name="static")
# Initialize ggwave instance
instance = ggwave.init()
# Initialize Groq client
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
class TextInput(BaseModel):
text: str
@app.get("/")
async def serve_homepage():
"""Serve the chat interface HTML."""
with open("static/conv.html", "r") as f:
return Response(content=f.read(), media_type="text/html")
@app.get("/conv/")
async def serve_convpage():
"""Serve the chat interface HTML."""
return FileResponse("static/index.html")
@app.post("/stt/")
async def speech_to_text(file: UploadFile = File(...)):
"""Convert WAV audio file to text using ggwave."""
with open("temp.wav", "wb") as audio_file:
audio_file.write(await file.read())
# Load WAV file
fs, recorded_waveform = wav.read("temp.wav")
os.remove("temp.wav")
# Convert to bytes and decode
waveform_bytes = recorded_waveform.astype(np.uint8).tobytes()
decoded_message = ggwave.decode(instance, waveform_bytes)
return {"text": decoded_message}
@app.post("/tts/")
def text_to_speech(input_text: TextInput):
"""Convert text to a WAV audio file using ggwave and return as response."""
encoded_waveform = ggwave.encode(input_text.text, protocolId=1, volume=100)
# Convert byte data into float32 array
waveform_float32 = np.frombuffer(encoded_waveform, dtype=np.float32)
# Normalize float32 data to the range of int16
waveform_int16 = np.int16(waveform_float32 * 32767)
# Save to buffer instead of a file
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wf:
wf.setnchannels(1) # Mono audio
wf.setsampwidth(2) # 2 bytes per sample (16-bit PCM)
wf.setframerate(48000) # Sample rate
wf.writeframes(waveform_int16.tobytes()) # Write waveform as bytes
buffer.seek(0)
return Response(content=buffer.getvalue(), media_type="audio/wav")
@app.post("/chat/")
async def chat_with_llm(file: UploadFile = File(...)):
"""Process input WAV, send text to LLM, and return generated response as WAV."""
global instance
# Read the file content into memory without saving to disk
file_content = await file.read()
# Create a BytesIO object to use with wav.read
with io.BytesIO(file_content) as buffer:
try:
fs, recorded_waveform = wav.read(buffer)
recorded_waveform = recorded_waveform.astype(np.float32) / 32767.0
waveform_bytes = recorded_waveform.tobytes()
user_message = ggwave.decode(instance, waveform_bytes)
if user_message is None:
return Response(
content="No message detected in audio",
media_type="text/plain",
status_code=400
)
print("user_message: " + user_message.decode("utf-8"))
# Send to LLM
chat_completion = client.chat.completions.create(
messages=[
{"role": "system", "content": "you are a helpful assistant. answer always in one sentence"},
{"role": "user", "content": user_message.decode("utf-8")}
],
model="llama-3.3-70b-versatile",
)
llm_response = chat_completion.choices[0].message.content
print(llm_response)
# Convert response to audio
encoded_waveform = ggwave.encode(llm_response, protocolId=1, volume=100)
# Convert byte data into float32 array
waveform_float32 = np.frombuffer(encoded_waveform, dtype=np.float32)
# Normalize float32 data to the range of int16
waveform_int16 = np.int16(waveform_float32 * 32767)
# Save to buffer instead of a file
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wf:
wf.setnchannels(1) # Mono audio
wf.setsampwidth(2) # 2 bytes per sample (16-bit PCM)
wf.setframerate(48000) # Sample rate
wf.writeframes(waveform_int16.tobytes()) # Write waveform as bytes
buffer.seek(0)
return Response(
content=buffer.getvalue(),
media_type="audio/wav",
headers={
"X-User-Message": user_message.decode("utf-8"),
"X-LLM-Response": llm_response
}
)
except Exception as e:
print(f"Error processing audio: {str(e)}")
return Response(
content=f"Error processing audio: {str(e)}",
media_type="text/plain",
status_code=500
)
@app.post("/continuous-chat/")
async def continuous_chat(
file: UploadFile = File(...),
chat_history: Optional[str] = Form(None)
):
"""Process input WAV with chat history, send text to LLM, and return response as WAV."""
global instance
# Parse chat history if provided
messages = [{"role": "system", "content": "you are a helpful assistant. answer always in one sentence"}]
if chat_history:
try:
history = json.loads(chat_history)
for msg in history:
if msg["role"] in ["user", "assistant"]:
messages.append(msg)
except Exception as e:
print(f"Error parsing chat history: {str(e)}")
# Read the file content into memory
file_content = await file.read()
# Process the audio file
with io.BytesIO(file_content) as buffer:
try:
fs, recorded_waveform = wav.read(buffer)
recorded_waveform = recorded_waveform.astype(np.float32) / 32767.0
waveform_bytes = recorded_waveform.tobytes()
user_message = ggwave.decode(instance, waveform_bytes)
if user_message is None:
return Response(
content="No message detected in audio",
media_type="text/plain",
status_code=400
)
decoded_message = user_message.decode("utf-8")
print("user_message: " + decoded_message)
# Add user message to messages
messages.append({"role": "user", "content": decoded_message})
# Send to LLM with full chat history
chat_completion = client.chat.completions.create(
messages=messages,
model="llama-3.3-70b-versatile",
)
llm_response = chat_completion.choices[0].message.content
print(llm_response)
# Convert response to audio
encoded_waveform = ggwave.encode(llm_response, protocolId=1, volume=100)
waveform_float32 = np.frombuffer(encoded_waveform, dtype=np.float32)
waveform_int16 = np.int16(waveform_float32 * 32767)
# Save to buffer
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(48000)
wf.writeframes(waveform_int16.tobytes())
buffer.seek(0)
return Response(
content=buffer.getvalue(),
media_type="audio/wav",
headers={
"X-User-Message": decoded_message,
"X-LLM-Response": llm_response
}
)
except Exception as e:
print(f"Error processing audio: {str(e)}")
return Response(
content=f"Error processing audio: {str(e)}",
media_type="text/plain",
status_code=500
) |