Update src/streamlit_app.py
Browse files- src/streamlit_app.py +38 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,40 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
import
|
|
|
|
| 4 |
import streamlit as st
|
| 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 |
-
))
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torchaudio
|
| 3 |
+
from transformers import WhisperProcessor, WhisperForConditionalGeneration
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 5 |
import streamlit as st
|
| 6 |
|
| 7 |
+
text_model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased")
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
|
| 9 |
+
whisper_processor = WhisperProcessor.from_pretrained("openai/whisper-tiny")
|
| 10 |
+
whisper_model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny")
|
| 11 |
+
|
| 12 |
+
def transcribe(audio_path):
|
| 13 |
+
waveform, sample_rate = torchaudio.load(audio_path)
|
| 14 |
+
input_features = whisper_processor(waveform.squeeze().numpy(), sampling_rate=sample_rate, return_tensors="pt").input_features
|
| 15 |
+
predicted_ids = whisper_model.generate(input_features)
|
| 16 |
+
transcription = whisper_processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
|
| 17 |
+
return transcription
|
| 18 |
+
|
| 19 |
+
def extract_text_features(text):
|
| 20 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 21 |
+
outputs = text_model(**inputs)
|
| 22 |
+
return outputs.logits.argmax(dim=1).item()
|
| 23 |
+
|
| 24 |
+
def predict_hate_speech(audio_path, text):
|
| 25 |
+
transcription = transcribe(audio_path)
|
| 26 |
+
text_input = text if text else transcription
|
| 27 |
+
prediction = extract_text_features(text_input)
|
| 28 |
+
return "Hate Speech" if prediction == 1 else "Not Hate Speech"
|
| 29 |
+
|
| 30 |
+
st.title("Hate Speech Detector with Audio and Text")
|
| 31 |
+
audio_file = st.file_uploader("Upload an audio file", type=["wav", "mp3", "flac"])
|
| 32 |
+
text_input = st.text_input("Optional text input")
|
| 33 |
+
if st.button("Predict"):
|
| 34 |
+
if audio_file is not None:
|
| 35 |
+
with open("temp_audio.wav", "wb") as f:
|
| 36 |
+
f.write(audio_file.read())
|
| 37 |
+
prediction = predict_hate_speech("temp_audio.wav", text_input)
|
| 38 |
+
st.success(prediction)
|
| 39 |
+
else:
|
| 40 |
+
st.warning("Please upload an audio file.")
|
|
|