Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import uvicorn
|
| 3 |
+
from fastapi import FastAPI, WebSocket
|
| 4 |
+
from fastapi.responses import HTMLResponse
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
import os
|
| 7 |
+
from voice_agent import CrewVoiceAgent
|
| 8 |
+
|
| 9 |
+
load_dotenv()
|
| 10 |
+
agent = CrewVoiceAgent()
|
| 11 |
+
|
| 12 |
+
app = FastAPI()
|
| 13 |
+
|
| 14 |
+
@app.get("/")
|
| 15 |
+
async def home():
|
| 16 |
+
return HTMLResponse("""
|
| 17 |
+
<html>
|
| 18 |
+
<body>
|
| 19 |
+
<h2>🎤 Gemini CrewAI Voice Agent</h2>
|
| 20 |
+
<button onclick="start()">Start</button>
|
| 21 |
+
<button onclick="stop()">Stop</button>
|
| 22 |
+
<p>Status: <span id='status'>Idle</span></p>
|
| 23 |
+
|
| 24 |
+
<script>
|
| 25 |
+
let ws;
|
| 26 |
+
let recorder;
|
| 27 |
+
|
| 28 |
+
async function start() {
|
| 29 |
+
ws = new WebSocket("wss://" + location.host + "/ws");
|
| 30 |
+
ws.onmessage = (event) => {
|
| 31 |
+
const audio = new Audio("data:audio/wav;base64," + event.data);
|
| 32 |
+
audio.play();
|
| 33 |
+
};
|
| 34 |
+
|
| 35 |
+
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
| 36 |
+
recorder = new MediaRecorder(stream, { mimeType: "audio/webm" });
|
| 37 |
+
|
| 38 |
+
recorder.ondataavailable = async (e) => {
|
| 39 |
+
const b = await e.data.arrayBuffer();
|
| 40 |
+
ws.send(b);
|
| 41 |
+
};
|
| 42 |
+
|
| 43 |
+
recorder.start(300);
|
| 44 |
+
document.getElementById("status").textContent = "Listening…";
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
function stop() {
|
| 48 |
+
recorder.stop();
|
| 49 |
+
ws.close();
|
| 50 |
+
document.getElementById("status").textContent = "Stopped";
|
| 51 |
+
}
|
| 52 |
+
</script>
|
| 53 |
+
</body>
|
| 54 |
+
</html>
|
| 55 |
+
""")
|
| 56 |
+
|
| 57 |
+
@app.websocket("/ws")
|
| 58 |
+
async def websocket_endpoint(ws: WebSocket):
|
| 59 |
+
await ws.accept()
|
| 60 |
+
|
| 61 |
+
async for audio_chunk in ws.iter_bytes():
|
| 62 |
+
response_audio = await agent.handle_audio(audio_chunk)
|
| 63 |
+
b64_audio = base64.b64encode(response_audio).decode()
|
| 64 |
+
|
| 65 |
+
await ws.send_text(b64_audio)
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|