moarafa97 commited on
Commit
01cef36
Β·
verified Β·
1 Parent(s): 82f26a0

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +18 -35
src/streamlit_app.py CHANGED
@@ -1,35 +1,32 @@
1
  import os
2
  import streamlit as st
3
 
4
- # Set app root dynamically
5
- APP_ROOT = os.path.dirname(os.path.abspath(__file__))
6
- MODEL_CACHE_DIR = os.path.join(APP_ROOT, "model_cache")
7
-
8
- # Set SpeechBrain cache path
9
- os.environ["SPEECHBRAIN_CACHE"] = MODEL_CACHE_DIR
10
-
11
- import streamlit as st
12
- import tempfile
13
- import requests
14
- import subprocess
15
- import torchaudio
16
  from speechbrain.pretrained.interfaces import foreign_class
17
 
 
 
 
 
18
 
 
 
 
 
 
 
19
  @st.cache_resource
20
  def load_model():
21
  try:
22
  return foreign_class(
23
  source="Jzuluaga/accent-id-commonaccent_xlsr-en-english",
24
  pymodule_file="custom_interface.py",
25
- classname="CustomEncoderWav2vec2Classifier",
26
- savedir=MODEL_CACHE_DIR
27
  )
28
  except Exception as e:
29
  st.error(f"❌ Model failed to load: {e}")
30
  raise
31
-
32
- # Download video from a public URL
33
  def download_video(url, temp_dir):
34
  video_path = os.path.join(temp_dir, "video.mp4")
35
  r = requests.get(url, stream=True)
@@ -38,11 +35,10 @@ def download_video(url, temp_dir):
38
  f.write(chunk)
39
  return video_path
40
 
41
- import imageio_ffmpeg
42
-
43
  def extract_audio(video_path, temp_dir):
44
  audio_path = os.path.join(temp_dir, "audio.wav")
45
- ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe() # Get bundled FFmpeg path
46
 
47
  command = [
48
  ffmpeg_path,
@@ -57,27 +53,16 @@ def extract_audio(video_path, temp_dir):
57
  raise RuntimeError(f"FFmpeg failed: {e}")
58
  return audio_path
59
 
 
60
  def classify_accent(audio_path, model):
61
  out_prob, score, index, label = model.classify_file(audio_path)
62
  return label, score * 100, out_prob
63
 
64
- # Streamlit UI
65
- st.set_page_config(page_title="Accent Classifier", layout="centered")
66
- st.title("English Accent Detection")
67
-
68
- st.markdown("Paste a link or upload a video to analyze the speaker's English accent.")
69
-
70
- video_url = st.text_input("Paste a direct link to a video (MP4 URL)")
71
- st.markdown("**OR**")
72
- uploaded_file = st.file_uploader("Upload a video file (MP4 format)", type=["mp4"])
73
-
74
-
75
-
76
  if uploaded_file or video_url:
77
  with st.spinner("Processing video..."):
78
  try:
79
  with tempfile.TemporaryDirectory() as temp_dir:
80
- # Get video path from upload or URL
81
  if uploaded_file:
82
  video_path = os.path.join(temp_dir, uploaded_file.name)
83
  with open(video_path, 'wb') as f:
@@ -89,11 +74,9 @@ if uploaded_file or video_url:
89
  model = load_model()
90
  label, confidence, probs = classify_accent(audio_path, model)
91
 
92
- # Ensure proper formatting
93
  label = label if isinstance(label, str) else label[0]
94
  st.success(f"Detected Accent: **{label}**")
95
- st.info(f"Confidence Score: **{confidence.item():.1f}%**")
96
 
97
-
98
  except Exception as e:
99
  st.error(f"❌ Error: {str(e)}")
 
1
  import os
2
  import streamlit as st
3
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from speechbrain.pretrained.interfaces import foreign_class
5
 
6
+ # Streamlit config
7
+ st.set_page_config(page_title="Accent Classifier", layout="centered")
8
+ st.title("English Accent Detection")
9
+ st.markdown("Paste a link or upload a video to analyze the speaker's English accent.")
10
 
11
+ # UI Inputs
12
+ video_url = st.text_input("Paste a direct link to a video (MP4 URL)")
13
+ st.markdown("**OR**")
14
+ uploaded_file = st.file_uploader("Upload a video file (MP4 format)", type=["mp4"])
15
+
16
+ # Load model (SpeechBrain default cache location)
17
  @st.cache_resource
18
  def load_model():
19
  try:
20
  return foreign_class(
21
  source="Jzuluaga/accent-id-commonaccent_xlsr-en-english",
22
  pymodule_file="custom_interface.py",
23
+ classname="CustomEncoderWav2vec2Classifier"
 
24
  )
25
  except Exception as e:
26
  st.error(f"❌ Model failed to load: {e}")
27
  raise
28
+
29
+ # Download video from URL
30
  def download_video(url, temp_dir):
31
  video_path = os.path.join(temp_dir, "video.mp4")
32
  r = requests.get(url, stream=True)
 
35
  f.write(chunk)
36
  return video_path
37
 
38
+ # Extract audio using bundled ffmpeg
 
39
  def extract_audio(video_path, temp_dir):
40
  audio_path = os.path.join(temp_dir, "audio.wav")
41
+ ffmpeg_path = imageio_ffmpeg.get_ffmpeg_exe()
42
 
43
  command = [
44
  ffmpeg_path,
 
53
  raise RuntimeError(f"FFmpeg failed: {e}")
54
  return audio_path
55
 
56
+ # Run classification
57
  def classify_accent(audio_path, model):
58
  out_prob, score, index, label = model.classify_file(audio_path)
59
  return label, score * 100, out_prob
60
 
61
+ # Main logic
 
 
 
 
 
 
 
 
 
 
 
62
  if uploaded_file or video_url:
63
  with st.spinner("Processing video..."):
64
  try:
65
  with tempfile.TemporaryDirectory() as temp_dir:
 
66
  if uploaded_file:
67
  video_path = os.path.join(temp_dir, uploaded_file.name)
68
  with open(video_path, 'wb') as f:
 
74
  model = load_model()
75
  label, confidence, probs = classify_accent(audio_path, model)
76
 
 
77
  label = label if isinstance(label, str) else label[0]
78
  st.success(f"Detected Accent: **{label}**")
79
+ st.info(f"Confidence Score: **{confidence:.1f}%**")
80
 
 
81
  except Exception as e:
82
  st.error(f"❌ Error: {str(e)}")