server run utility
Browse files- app.py +15 -128
- requirements.txt +3 -2
- server.py +131 -0
app.py
CHANGED
|
@@ -1,133 +1,20 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi.staticfiles import StaticFiles
|
| 3 |
-
from fastapi.responses import HTMLResponse
|
| 4 |
-
from fastapi.templating import Jinja2Templates
|
| 5 |
import os
|
| 6 |
-
import
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
import torch
|
| 11 |
-
from transformers.pipelines.audio_utils import ffmpeg_microphone_live
|
| 12 |
-
|
| 13 |
-
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 14 |
-
|
| 15 |
-
classifier = pipeline(
|
| 16 |
-
"audio-classification", model="MIT/ast-finetuned-speech-commands-v2", device=device
|
| 17 |
-
)
|
| 18 |
-
intent_class_pipe = pipeline(
|
| 19 |
-
"audio-classification", model="anton-l/xtreme_s_xlsr_minds14", device=device
|
| 20 |
-
)
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
async def launch_fn(
|
| 24 |
-
wake_word="marvin",
|
| 25 |
-
prob_threshold=0.5,
|
| 26 |
-
chunk_length_s=2.0,
|
| 27 |
-
stream_chunk_s=0.25,
|
| 28 |
-
debug=False,
|
| 29 |
-
):
|
| 30 |
-
if wake_word not in classifier.model.config.label2id.keys():
|
| 31 |
-
raise ValueError(
|
| 32 |
-
f"Wake word {wake_word} not in set of valid class labels, pick a wake word in the set {classifier.model.config.label2id.keys()}."
|
| 33 |
-
)
|
| 34 |
-
|
| 35 |
-
sampling_rate = classifier.feature_extractor.sampling_rate
|
| 36 |
-
|
| 37 |
-
mic = ffmpeg_microphone_live(
|
| 38 |
-
sampling_rate=sampling_rate,
|
| 39 |
-
chunk_length_s=chunk_length_s,
|
| 40 |
-
stream_chunk_s=stream_chunk_s,
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
print("Listening for wake word...")
|
| 44 |
-
for prediction in classifier(mic):
|
| 45 |
-
prediction = prediction[0]
|
| 46 |
-
if debug:
|
| 47 |
-
print(prediction)
|
| 48 |
-
if prediction["label"] == wake_word:
|
| 49 |
-
if prediction["score"] > prob_threshold:
|
| 50 |
-
return True
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
async def listen(websocket, chunk_length_s=2.0, stream_chunk_s=2.0):
|
| 54 |
-
sampling_rate = intent_class_pipe.feature_extractor.sampling_rate
|
| 55 |
-
|
| 56 |
-
mic = ffmpeg_microphone_live(
|
| 57 |
-
sampling_rate=sampling_rate,
|
| 58 |
-
chunk_length_s=chunk_length_s,
|
| 59 |
-
stream_chunk_s=stream_chunk_s,
|
| 60 |
-
)
|
| 61 |
-
audio_buffer = []
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
audio_buffer.append(audio_chunk["raw"])
|
| 67 |
-
|
| 68 |
-
prediction = intent_class_pipe(audio_chunk["raw"])
|
| 69 |
-
await websocket.send_text(f"chunk: {prediction[0]['label']} | {i+1} / 4")
|
| 70 |
-
|
| 71 |
-
if await is_silence(audio_chunk["raw"], threshold=0.7):
|
| 72 |
-
print("Silence detected, processing audio.")
|
| 73 |
-
break
|
| 74 |
-
|
| 75 |
-
combined_audio = np.concatenate(audio_buffer)
|
| 76 |
-
prediction = intent_class_pipe(combined_audio)
|
| 77 |
-
top_3_predictions = prediction[:3]
|
| 78 |
-
formatted_predictions = "\n".join([f"{pred['label']}: {pred['score'] * 100:.2f}%" for pred in top_3_predictions])
|
| 79 |
-
await websocket.send_text(f"classes: \n{formatted_predictions}")
|
| 80 |
-
return
|
| 81 |
-
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
return True
|
| 87 |
else:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
app = FastAPI()
|
| 93 |
-
|
| 94 |
-
# Set up static file directory
|
| 95 |
-
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 96 |
-
|
| 97 |
-
# Jinja2 Template for HTML rendering
|
| 98 |
-
templates = Jinja2Templates(directory="templates")
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
@app.get("/", response_class=HTMLResponse)
|
| 102 |
-
async def get_home(request: Request):
|
| 103 |
-
return templates.TemplateResponse("index.html", {"request": request})
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
@app.websocket("/ws")
|
| 107 |
-
async def websocket_endpoint(websocket: WebSocket):
|
| 108 |
-
await websocket.accept()
|
| 109 |
-
try:
|
| 110 |
-
process_active = False # Flag to track the state of the process
|
| 111 |
-
|
| 112 |
-
while True:
|
| 113 |
-
message = await websocket.receive_text()
|
| 114 |
-
|
| 115 |
-
if message == "start" and not process_active:
|
| 116 |
-
process_active = True
|
| 117 |
-
await websocket.send_text("Listening for wake word...")
|
| 118 |
-
wake_word_detected = await launch_fn(debug=True)
|
| 119 |
-
if wake_word_detected:
|
| 120 |
-
await websocket.send_text("Wake word detected. Listening for your query...")
|
| 121 |
-
await listen(websocket)
|
| 122 |
-
process_active = False # Reset the process flag
|
| 123 |
-
|
| 124 |
-
elif message == "stop":
|
| 125 |
-
if process_active:
|
| 126 |
-
# Implement logic to stop the ongoing process
|
| 127 |
-
# This might involve setting a flag that your launch_fn and listen functions check
|
| 128 |
-
process_active = False
|
| 129 |
-
await websocket.send_text("Process stopped. Ready to restart.")
|
| 130 |
-
break # Or keep the loop running if you want to allow restarting without reconnecting
|
| 131 |
-
|
| 132 |
-
except WebSocketDisconnect:
|
| 133 |
-
print("Client disconnected.")
|
|
|
|
| 1 |
+
import json
|
|
|
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
+
import requests
|
| 4 |
+
import socket
|
| 5 |
|
| 6 |
+
def start_server():
|
| 7 |
+
os.system("uvicorn server:app --port 8080 --host 0.0.0.0 --workers 2")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
def is_port_in_use(port):
|
| 10 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 11 |
+
return s.connect_ex(('0.0.0.0', port)) == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
def main():
|
| 14 |
+
if is_port_in_use(8080):
|
| 15 |
+
print("Port 8080 is already in use. Please kill the process and try again.")
|
|
|
|
| 16 |
else:
|
| 17 |
+
start_server()
|
| 18 |
+
|
| 19 |
+
if __name__ == "__main__":
|
| 20 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -3,5 +3,6 @@ transformers
|
|
| 3 |
torchaudio
|
| 4 |
numpy
|
| 5 |
fastapi
|
| 6 |
-
uvicorn
|
| 7 |
-
gradio
|
|
|
|
|
|
| 3 |
torchaudio
|
| 4 |
numpy
|
| 5 |
fastapi
|
| 6 |
+
uvicorn
|
| 7 |
+
gradio
|
| 8 |
+
requests
|
server.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, WebSocket, Request, WebSocketDisconnect
|
| 2 |
+
from fastapi.staticfiles import StaticFiles
|
| 3 |
+
from fastapi.responses import HTMLResponse
|
| 4 |
+
from fastapi.templating import Jinja2Templates
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from transformers import pipeline
|
| 8 |
+
import torch
|
| 9 |
+
from transformers.pipelines.audio_utils import ffmpeg_microphone_live
|
| 10 |
+
|
| 11 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 12 |
+
|
| 13 |
+
classifier = pipeline(
|
| 14 |
+
"audio-classification", model="MIT/ast-finetuned-speech-commands-v2", device=device
|
| 15 |
+
)
|
| 16 |
+
intent_class_pipe = pipeline(
|
| 17 |
+
"audio-classification", model="anton-l/xtreme_s_xlsr_minds14", device=device
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
async def launch_fn(
|
| 22 |
+
wake_word="marvin",
|
| 23 |
+
prob_threshold=0.5,
|
| 24 |
+
chunk_length_s=2.0,
|
| 25 |
+
stream_chunk_s=0.25,
|
| 26 |
+
debug=False,
|
| 27 |
+
):
|
| 28 |
+
if wake_word not in classifier.model.config.label2id.keys():
|
| 29 |
+
raise ValueError(
|
| 30 |
+
f"Wake word {wake_word} not in set of valid class labels, pick a wake word in the set {classifier.model.config.label2id.keys()}."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
sampling_rate = classifier.feature_extractor.sampling_rate
|
| 34 |
+
|
| 35 |
+
mic = ffmpeg_microphone_live(
|
| 36 |
+
sampling_rate=sampling_rate,
|
| 37 |
+
chunk_length_s=chunk_length_s,
|
| 38 |
+
stream_chunk_s=stream_chunk_s,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
print("Listening for wake word...")
|
| 42 |
+
for prediction in classifier(mic):
|
| 43 |
+
prediction = prediction[0]
|
| 44 |
+
if debug:
|
| 45 |
+
print(prediction)
|
| 46 |
+
if prediction["label"] == wake_word:
|
| 47 |
+
if prediction["score"] > prob_threshold:
|
| 48 |
+
return True
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
async def listen(websocket, chunk_length_s=2.0, stream_chunk_s=2.0):
|
| 52 |
+
sampling_rate = intent_class_pipe.feature_extractor.sampling_rate
|
| 53 |
+
|
| 54 |
+
mic = ffmpeg_microphone_live(
|
| 55 |
+
sampling_rate=sampling_rate,
|
| 56 |
+
chunk_length_s=chunk_length_s,
|
| 57 |
+
stream_chunk_s=stream_chunk_s,
|
| 58 |
+
)
|
| 59 |
+
audio_buffer = []
|
| 60 |
+
|
| 61 |
+
print("Listening")
|
| 62 |
+
for i in range(4):
|
| 63 |
+
audio_chunk = next(mic)
|
| 64 |
+
audio_buffer.append(audio_chunk["raw"])
|
| 65 |
+
|
| 66 |
+
prediction = intent_class_pipe(audio_chunk["raw"])
|
| 67 |
+
await websocket.send_text(f"chunk: {prediction[0]['label']} | {i+1} / 4")
|
| 68 |
+
|
| 69 |
+
if await is_silence(audio_chunk["raw"], threshold=0.7):
|
| 70 |
+
print("Silence detected, processing audio.")
|
| 71 |
+
break
|
| 72 |
+
|
| 73 |
+
combined_audio = np.concatenate(audio_buffer)
|
| 74 |
+
prediction = intent_class_pipe(combined_audio)
|
| 75 |
+
top_3_predictions = prediction[:3]
|
| 76 |
+
formatted_predictions = "\n".join([f"{pred['label']}: {pred['score'] * 100:.2f}%" for pred in top_3_predictions])
|
| 77 |
+
await websocket.send_text(f"classes: \n{formatted_predictions}")
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
async def is_silence(audio_chunk, threshold):
|
| 82 |
+
silence = intent_class_pipe(audio_chunk)
|
| 83 |
+
if silence[0]["label"] == "silence" and silence[0]["score"] > threshold:
|
| 84 |
+
return True
|
| 85 |
+
else:
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Initialize FastAPI app
|
| 90 |
+
app = FastAPI()
|
| 91 |
+
|
| 92 |
+
# Set up static file directory
|
| 93 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 94 |
+
|
| 95 |
+
# Jinja2 Template for HTML rendering
|
| 96 |
+
templates = Jinja2Templates(directory="templates")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@app.get("/", response_class=HTMLResponse)
|
| 100 |
+
async def get_home(request: Request):
|
| 101 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@app.websocket("/ws")
|
| 105 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 106 |
+
await websocket.accept()
|
| 107 |
+
try:
|
| 108 |
+
process_active = False # Flag to track the state of the process
|
| 109 |
+
|
| 110 |
+
while True:
|
| 111 |
+
message = await websocket.receive_text()
|
| 112 |
+
|
| 113 |
+
if message == "start" and not process_active:
|
| 114 |
+
process_active = True
|
| 115 |
+
await websocket.send_text("Listening for wake word...")
|
| 116 |
+
wake_word_detected = await launch_fn(debug=True)
|
| 117 |
+
if wake_word_detected:
|
| 118 |
+
await websocket.send_text("Wake word detected. Listening for your query...")
|
| 119 |
+
await listen(websocket)
|
| 120 |
+
process_active = False # Reset the process flag
|
| 121 |
+
|
| 122 |
+
elif message == "stop":
|
| 123 |
+
if process_active:
|
| 124 |
+
# Implement logic to stop the ongoing process
|
| 125 |
+
# This might involve setting a flag that your launch_fn and listen functions check
|
| 126 |
+
process_active = False
|
| 127 |
+
await websocket.send_text("Process stopped. Ready to restart.")
|
| 128 |
+
break # Or keep the loop running if you want to allow restarting without reconnecting
|
| 129 |
+
|
| 130 |
+
except WebSocketDisconnect:
|
| 131 |
+
print("Client disconnected.")
|