Update app.py
Browse files
app.py
CHANGED
|
@@ -1,94 +1,116 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
import numpy as np
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
# Hugging Face
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
model
|
| 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 |
-
"alert_type": alert_type
|
| 61 |
-
}
|
| 62 |
-
return send_salesforce_alert(alert_data)
|
| 63 |
-
|
| 64 |
-
# API Endpoint for uploading audio file and processing it
|
| 65 |
-
@app.post("/upload-audio/")
|
| 66 |
-
async def upload_audio(file: UploadFile = File(...)):
|
| 67 |
-
"""
|
| 68 |
-
Handles audio file upload, processes the audio for panic detection,
|
| 69 |
-
and triggers an alert if necessary.
|
| 70 |
-
"""
|
| 71 |
-
# Save the uploaded file temporarily
|
| 72 |
-
file_location = f"./temp_audio/{file.filename}"
|
| 73 |
-
with open(file_location, "wb") as audio_file:
|
| 74 |
-
audio_file.write(file.file.read())
|
| 75 |
-
|
| 76 |
-
# Process audio to detect panic/scream
|
| 77 |
-
detection_result = process_audio(file_location)
|
| 78 |
-
|
| 79 |
-
# Set alert type based on confidence
|
| 80 |
-
alert_type = "High-Risk" if detection_result == 1 else "Medium-Risk"
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
#
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
Start or stop the detection system.
|
| 93 |
-
"""
|
| 94 |
-
return {"message": f"Detection system {status}"}
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import sounddevice as sd
|
| 3 |
import numpy as np
|
| 4 |
+
import librosa
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2ForSequenceClassification
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
# Configure logging
|
| 10 |
+
logging.basicConfig(level=logging.INFO)
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
# Load Hugging Face model
|
| 14 |
+
MODEL_NAME = "ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition"
|
| 15 |
+
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_NAME)
|
| 16 |
+
model = Wav2Vec2ForSequenceClassification.from_pretrained(MODEL_NAME)
|
| 17 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
model.to(device)
|
| 19 |
+
model.eval()
|
| 20 |
+
logger.info(f"Loaded model {MODEL_NAME} on {device}")
|
| 21 |
+
|
| 22 |
+
# Audio settings
|
| 23 |
+
SAMPLE_RATE = 16000 # Model expects 16kHz
|
| 24 |
+
DURATION = 5 # Seconds for real-time audio chunks
|
| 25 |
+
recording = None
|
| 26 |
+
is_recording = False
|
| 27 |
+
|
| 28 |
+
# Function to process audio and detect screams
|
| 29 |
+
def process_audio(audio_data, sample_rate=SAMPLE_RATE):
|
| 30 |
+
try:
|
| 31 |
+
inputs = feature_extractor(audio_data, sampling_rate=sample_rate, return_tensors="pt", padding=True)
|
| 32 |
+
inputs = {key: val.to(device) for key, val in inputs.items()}
|
| 33 |
+
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
outputs = model(**inputs)
|
| 36 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 37 |
+
confidence, predicted_label = torch.max(probabilities, dim=-1)
|
| 38 |
+
confidence = confidence.item() * 100
|
| 39 |
+
label = model.config.id2label[predicted_label.item()]
|
| 40 |
+
|
| 41 |
+
# Check for scream-like emotions (e.g., fear, surprise)
|
| 42 |
+
scream_detected = label in ["fear", "surprise"]
|
| 43 |
+
risk_level = None
|
| 44 |
+
if scream_detected:
|
| 45 |
+
if confidence > 80:
|
| 46 |
+
risk_level = "High-Risk"
|
| 47 |
+
elif 50 <= confidence <= 80:
|
| 48 |
+
risk_level = "Medium-Risk"
|
| 49 |
+
|
| 50 |
+
return scream_detected, confidence, label, risk_level
|
| 51 |
+
except Exception as e:
|
| 52 |
+
logger.error(f"Error processing audio: {e}")
|
| 53 |
+
return False, 0, "error", None
|
| 54 |
+
|
| 55 |
+
# Real-time audio capture
|
| 56 |
+
def start_recording():
|
| 57 |
+
global recording, is_recording
|
| 58 |
+
is_recording = True
|
| 59 |
+
recording = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
def callback(indata, frames, time, status):
|
| 62 |
+
if status:
|
| 63 |
+
logger.error(f"Recording error: {status}")
|
| 64 |
+
recording.append(indata.copy())
|
| 65 |
+
|
| 66 |
+
logger.info("Starting real-time audio capture")
|
| 67 |
+
with sd.InputStream(samplerate=SAMPLE_RATE, channels=1, callback=callback, blocksize=int(SAMPLE_RATE * DURATION)):
|
| 68 |
+
while is_recording:
|
| 69 |
+
sd.sleep(1000)
|
| 70 |
+
|
| 71 |
+
return "Recording started"
|
| 72 |
+
|
| 73 |
+
def stop_recording():
|
| 74 |
+
global is_recording, recording
|
| 75 |
+
is_recording = False
|
| 76 |
+
if recording:
|
| 77 |
+
audio_data = np.concatenate(recording, axis=0).flatten()
|
| 78 |
+
scream_detected, confidence, label, risk_level = process_audio(audio_data)
|
| 79 |
+
return f"Detection: {scream_detected}, Confidence: {confidence:.2f}%, Label: {label}, Risk: {risk_level}"
|
| 80 |
+
return "No audio recorded"
|
| 81 |
+
|
| 82 |
+
# Process uploaded audio file
|
| 83 |
+
def process_uploaded_audio(audio_file):
|
| 84 |
+
try:
|
| 85 |
+
audio_data, sr = librosa.load(audio_file, sr=SAMPLE_RATE)
|
| 86 |
+
scream_detected, confidence, label, risk_level = process_audio(audio_data, sr)
|
| 87 |
+
return f"Detection: {scream_detected}, Confidence: {confidence:.2f}%, Label: {label}, Risk: {risk_level}"
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logger.error(f"Error processing uploaded audio: {e}")
|
| 90 |
+
return f"Error: {e}"
|
| 91 |
+
|
| 92 |
+
# Gradio interface
|
| 93 |
+
def create_interface():
|
| 94 |
+
with gr.Blocks() as demo:
|
| 95 |
+
gr.Markdown("# Scream Detection System")
|
| 96 |
+
|
| 97 |
+
with gr.Row():
|
| 98 |
+
start_btn = gr.Button("Start Recording")
|
| 99 |
+
stop_btn = gr.Button("Stop Recording")
|
| 100 |
+
|
| 101 |
+
upload = gr.Audio(source="upload", type="filepath", label="Upload Audio File")
|
| 102 |
+
output = gr.Textbox(label="Detection Results")
|
| 103 |
+
|
| 104 |
+
with gr.Accordion("Settings"):
|
| 105 |
+
confidence_threshold = gr.Slider(50, 100, value=80, label="High-Risk Confidence Threshold")
|
| 106 |
+
|
| 107 |
+
start_btn.click(start_recording, outputs=output)
|
| 108 |
+
stop_btn.click(stop_recording, outputs=output)
|
| 109 |
+
upload.change(process_uploaded_audio, inputs=upload, outputs=output)
|
| 110 |
+
|
| 111 |
+
return demo
|
| 112 |
|
| 113 |
+
# Launch the interface
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
demo = create_interface()
|
| 116 |
+
demo.launch()
|
|
|
|
|
|
|
|
|