CoolFace
Apppublic

WonRvn/OSP_21_Fall_Detection

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
app.py82 linesDownload Raw Back to root
1import streamlit as st2import numpy as np3import torch4import librosa5import pyaudio6import pygame7from sklearn.preprocessing import StandardScaler8from sklearn.svm import SVC9from sklearn.model_selection import train_test_split10import os11import pandas as pd12 13# Streamlit app title14st.title('Real-time Fall Detection System')15 16# Load trained model and utilities17vad_model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad', force_reload=True)18(get_speech_timestamps, save_audio, read_audio, VADIterator, collect_chunks) = utils19 20# Load trained SVM model and scaler (replace with your own model and scaler paths)21svm_model = SVC(C=64.88135039273247, kernel='linear', gamma='scale')  # Load your trained SVM model here22svm_scaler = StandardScaler()  # Load your trained scaler here23 24# Function to convert int16 audio to float25def int2float(sound):26    abs_max = np.abs(sound).max()27    sound = sound.astype('float32')28    if abs_max > 0:29        sound *= 1 / 3276830    sound = sound.squeeze()31    return sound32 33# Function to process audio for real-time fall detection34def process_audio_for_fall_detection(audio_chunk):35    # Convert the audio to a suitable format36    audio_int16 = np.frombuffer(audio_chunk, np.int16)37    audio_float32 = int2float(audio_int16)38    waveform = audio_float3239 40    # Extract MFCC features (adjust n_mfcc based on your model)41    n_mfcc = 13  # Replace this with the number of MFCCs used in your model42    mfcc_features = librosa.feature.mfcc(y=waveform, sr=16000, n_mfcc=n_mfcc)43    mfcc_aggregated = np.mean(mfcc_features, axis=1).reshape(1, -1)44 45    # Scale features46    mfcc_scaled = svm_scaler.transform(mfcc_aggregated)47 48    # Predict fall detection49    fall_detection_prediction = svm_model.predict(mfcc_scaled)50    return fall_detection_prediction51 52# Streamlit button to start fall detection53if st.button('Start Fall Detection'):54    FORMAT = pyaudio.paInt1655    CHANNELS = 156    RATE = 1600057    CHUNK = 102458    audio = pyaudio.PyAudio()59    stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)60 61    st.write("Listening for falls...")62    try:63        while True:64            audio_chunk = stream.read(CHUNK)65            prediction = process_audio_for_fall_detection(audio_chunk)66            if prediction == 1:  # Assuming 1 indicates a fall67                st.write("Fall detected!")68                break69    except KeyboardInterrupt:70        pass71 72    stream.stop_stream()73    stream.close()74    audio.terminate()75 76# Function to play an audio alert77def play_audio_alert(audio_file):78    pygame.mixer.init()79    pygame.mixer.music.load(audio_file)80    pygame.mixer.music.play()81 82