TaahKay commited on
Commit
4a9476d
Β·
verified Β·
1 Parent(s): 66b3183

Upload 13 files

Browse files
.streamlit/config.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [server]
2
+ fileWatcherType = "none"
3
+ maxUploadSize = 70
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ryan Kembo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import tempfile
3
+ import shutil
4
+ import psutil
5
+ import torch
6
+ import torchaudio
7
+
8
+ from utils.audio_processing import trim_audio, download_audio_as_wav
9
+ from utils.video_processing import trim_video
10
+ from models.model_loader import load_accent_model, load_whisper
11
+ from utils.accent_analysis import analyze_accent
12
+ from utils.session_utils import initialize_session_state, display_memory_once, reset_session_state_except_model
13
+ from models.custom_interface import CustomEncoderWav2vec2Classifier
14
+
15
+ st.title("πŸŽ™οΈ English Accent Audio Detector")
16
+
17
+ # Initialize session state
18
+ initialize_session_state()
19
+
20
+ # Load models once
21
+ if 'classifier' not in st.session_state:
22
+ st.session_state.classifier = load_accent_model()
23
+ if 'whisper' not in st.session_state:
24
+ st.session_state.whisper = load_whisper()
25
+
26
+ # Memory info
27
+ display_memory_once()
28
+
29
+ # Reset state for a new analysis
30
+ if st.button("πŸ”„ Analyze new video"):
31
+ reset_session_state_except_model()
32
+ st.rerun()
33
+
34
+ # Check for ffmpeg
35
+ if not shutil.which("ffmpeg"):
36
+ raise EnvironmentError("FFmpeg not found. Please install or add it to PATH.")
37
+
38
+ # Input options
39
+ option = st.radio("Choose input method:", ["Upload video file", "Enter Video Url"])
40
+
41
+ if option == "Upload video file":
42
+ uploaded_video = st.file_uploader("Upload your video", type=["mp4", "mov", "avi", "mkv"])
43
+ if uploaded_video is not None:
44
+ temp_video_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
45
+ with open(temp_video_path.name, "wb") as f:
46
+ f.write(uploaded_video.read())
47
+ audio_path = trim_video(temp_video_path.name)
48
+ st.success("βœ… Video uploaded successfully.")
49
+ st.session_state.audio_path = audio_path
50
+
51
+
52
+ elif option == "Enter Video Url":
53
+ yt_url = st.text_input("Paste YouTube URL")
54
+ if st.button("Download Video"):
55
+ with st.spinner("Downloading video..."):
56
+ audio_path = download_audio_as_wav(yt_url)
57
+ audio_path = trim_audio(audio_path)
58
+ if audio_path:
59
+ st.success("βœ… Video downloaded successfully.")
60
+ st.session_state.audio_path = audio_path
61
+
62
+
63
+ # Transcription and Accent Analysis
64
+ if st.session_state.audio_path and not st.session_state.transcription:
65
+ if st.button("🎧 Extract Audio"):
66
+ st.session_state.audio_ready = True
67
+ st.audio(st.session_state.audio_path, format='audio/wav')
68
+
69
+ mem = psutil.virtual_memory()
70
+ st.write(f"πŸ” Memory used: {mem.percent}%")
71
+ #Detect Language AND FILTER OUT NON-ENGLISH AUDIOS FOR ANALYSIS
72
+ segments, info = st.session_state.whisper.transcribe(st.session_state.audio_path, beam_size=1)
73
+
74
+ # Convert segments (generator) to full transcription string
75
+ st.session_state.transcription = " ".join([segment.text for segment in segments])
76
+
77
+ if info.language != "en":
78
+
79
+ st.error("❌ This video does not appear to be in English. Please provide a clear English video.")
80
+ else:
81
+ # Show transcription for audio
82
+ with st.spinner("Transcribing audio..."):
83
+ st.markdown(" Transcript Preview")
84
+ st.markdown(st.session_state.transcription)
85
+ st.success("🎡 Audio extracted and ready for analysis!")
86
+ mem = psutil.virtual_memory()
87
+ st.write(f"πŸ” Memory used: {mem.percent}%")
88
+
89
+
90
+
91
+ if st.session_state.transcription:
92
+ if st.button("πŸ—£οΈ Analyze Accent"):
93
+ with st.spinner("πŸ” Analyzing accent..."):
94
+ try:
95
+ mem = psutil.virtual_memory()
96
+ st.write(f"πŸ” Memory used: {mem.percent}%")
97
+ waveform, sample_rate = torchaudio.load(st.session_state.audio_path)
98
+ readable_accent, confidence = analyze_accent(waveform, sample_rate, st.session_state.classifier)
99
+
100
+ if readable_accent:
101
+ st.success(f"βœ… Accent Detected: **{readable_accent}**")
102
+ st.info(f"πŸ“Š Confidence: {confidence}%")
103
+
104
+ else:
105
+ st.warning("Could not determine accent.")
106
+
107
+ except Exception as e:
108
+ st.error("❌ Failed to analyze accent.")
109
+ st.code(str(e))
models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
models/custom_interface.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ from speechbrain.pretrained import Pretrained
4
+
5
+
6
+ class CustomEncoderWav2vec2Classifier(Pretrained):
7
+ """A ready-to-use class for utterance-level classification (e.g, speaker-id,
8
+ language-id, emotion recognition, keyword spotting, etc).
9
+ The class assumes that an self-supervised encoder like wav2vec2/hubert and a classifier model
10
+ are defined in the yaml file. If you want to
11
+ convert the predicted index into a corresponding text label, please
12
+ provide the path of the label_encoder in a variable called 'lab_encoder_file'
13
+ within the yaml.
14
+ The class can be used either to run only the encoder (encode_batch()) to
15
+ extract embeddings or to run a classification step (classify_batch()).
16
+ ```
17
+ Example
18
+ -------
19
+ >>> import torchaudio
20
+ >>> from speechbrain.pretrained import EncoderClassifier
21
+ >>> # Model is downloaded from the speechbrain HuggingFace repo
22
+ >>> tmpdir = getfixture("tmpdir")
23
+ >>> classifier = EncoderClassifier.from_hparams(
24
+ ... source="speechbrain/spkrec-ecapa-voxceleb",
25
+ ... savedir=tmpdir,
26
+ ... )
27
+ >>> # Compute embeddings
28
+ >>> signal, fs = torchaudio.load("samples/audio_samples/example1.wav")
29
+ >>> embeddings = classifier.encode_batch(signal)
30
+ >>> # Classification
31
+ >>> prediction = classifier .classify_batch(signal)
32
+ """
33
+
34
+ def __init__(self, *args, **kwargs):
35
+ super().__init__(*args, **kwargs)
36
+
37
+ def encode_batch(self, wavs, wav_lens=None, normalize=False):
38
+ """Encodes the input audio into a single vector embedding.
39
+ The waveforms should already be in the model's desired format.
40
+ You can call:
41
+ ``normalized = <this>.normalizer(signal, sample_rate)``
42
+ to get a correctly converted signal in most cases.
43
+ Arguments
44
+ ---------
45
+ wavs : torch.tensor
46
+ Batch of waveforms [batch, time, channels] or [batch, time]
47
+ depending on the model. Make sure the sample rate is fs=16000 Hz.
48
+ wav_lens : torch.tensor
49
+ Lengths of the waveforms relative to the longest one in the
50
+ batch, tensor of shape [batch]. The longest one should have
51
+ relative length 1.0 and others len(waveform) / max_length.
52
+ Used for ignoring padding.
53
+ normalize : bool
54
+ If True, it normalizes the embeddings with the statistics
55
+ contained in mean_var_norm_emb.
56
+ Returns
57
+ -------
58
+ torch.tensor
59
+ The encoded batch
60
+ """
61
+ # Manage single waveforms in input
62
+ if len(wavs.shape) == 1:
63
+ wavs = wavs.unsqueeze(0)
64
+
65
+ # Assign full length if wav_lens is not assigned
66
+ if wav_lens is None:
67
+ wav_lens = torch.ones(wavs.shape[0], device=self.device)
68
+
69
+ # Storing waveform in the specified device
70
+ wavs, wav_lens = wavs.to(self.device), wav_lens.to(self.device)
71
+ wavs = wavs.float()
72
+
73
+ # Computing features and embeddings
74
+ outputs = self.mods.wav2vec2(wavs)
75
+
76
+ # last dim will be used for AdaptativeAVG pool
77
+ outputs = self.mods.avg_pool(outputs, wav_lens)
78
+ outputs = outputs.view(outputs.shape[0], -1)
79
+ return outputs
80
+
81
+ def classify_batch(self, wavs, wav_lens=None):
82
+ """Performs classification on the top of the encoded features.
83
+ It returns the posterior probabilities, the index and, if the label
84
+ encoder is specified it also the text label.
85
+ Arguments
86
+ ---------
87
+ wavs : torch.tensor
88
+ Batch of waveforms [batch, time, channels] or [batch, time]
89
+ depending on the model. Make sure the sample rate is fs=16000 Hz.
90
+ wav_lens : torch.tensor
91
+ Lengths of the waveforms relative to the longest one in the
92
+ batch, tensor of shape [batch]. The longest one should have
93
+ relative length 1.0 and others len(waveform) / max_length.
94
+ Used for ignoring padding.
95
+ Returns
96
+ -------
97
+ out_prob
98
+ The log posterior probabilities of each class ([batch, N_class])
99
+ score:
100
+ It is the value of the log-posterior for the best class ([batch,])
101
+ index
102
+ The indexes of the best class ([batch,])
103
+ text_lab:
104
+ List with the text labels corresponding to the indexes.
105
+ (label encoder should be provided).
106
+ """
107
+ outputs = self.encode_batch(wavs, wav_lens)
108
+ outputs = self.mods.output_mlp(outputs)
109
+ out_prob = self.hparams.softmax(outputs)
110
+ score, index = torch.max(out_prob, dim=-1)
111
+ text_lab = self.hparams.label_encoder.decode_torch(index)
112
+ return out_prob, score, index, text_lab
113
+
114
+ def classify_file(self, path):
115
+ """Classifies the given audiofile into the given set of labels.
116
+ Arguments
117
+ ---------
118
+ path : str
119
+ Path to audio file to classify.
120
+ Returns
121
+ -------
122
+ out_prob
123
+ The log posterior probabilities of each class ([batch, N_class])
124
+ score:
125
+ It is the value of the log-posterior for the best class ([batch,])
126
+ index
127
+ The indexes of the best class ([batch,])
128
+ text_lab:
129
+ List with the text labels corresponding to the indexes.
130
+ (label encoder should be provided).
131
+ """
132
+ waveform = self.load_audio(path)
133
+ # Fake a batch:
134
+ batch = waveform.unsqueeze(0)
135
+ rel_length = torch.tensor([1.0])
136
+ outputs = self.encode_batch(batch, rel_length)
137
+ outputs = self.mods.output_mlp(outputs).squeeze(1)
138
+ out_prob = self.hparams.softmax(outputs)
139
+ score, index = torch.max(out_prob, dim=-1)
140
+ text_lab = self.hparams.label_encoder.decode_torch(index)
141
+ return out_prob, score, index, text_lab
142
+
143
+ def forward(self, wavs, wav_lens=None, normalize=False):
144
+ return self.encode_batch(
145
+ wavs=wavs, wav_lens=wav_lens, normalize=normalize
146
+ )
models/model_loader.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from speechbrain.pretrained.interfaces import foreign_class
4
+ from faster_whisper import WhisperModel
5
+
6
+
7
+ # -------------------------------
8
+ # Load Model (Cached)
9
+ # -------------------------------
10
+ @st.cache_resource(show_spinner="Loading model...") # making sure we only load the model once per every app instance
11
+ def load_accent_model():
12
+ """Loads custom accent classification model."""
13
+ if not os.getenv("HF_TOKEN"):
14
+ st.error("Hugging Face token not found.")
15
+ st.stop()
16
+ try:
17
+ return foreign_class(
18
+ source="Jzuluaga/accent-id-commonaccent_xlsr-en-english",
19
+ pymodule_file="custom_interface.py",
20
+ classname="CustomEncoderWav2vec2Classifier"
21
+ )
22
+ except Exception as e:
23
+ st.error(f"❌ Error loading model: {e}")
24
+ st.stop()
25
+
26
+ @st.cache_resource(show_spinner="Loading Whisper...")
27
+ def load_whisper():
28
+ return WhisperModel("tiny", device="cpu", compute_type="int8_float32")
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt CHANGED
@@ -1,3 +1,29 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ moviepy
3
+ ffmpeg-python
4
+ requests
5
+ speechbrain==0.5.14
6
+ faster-whisper
7
+ transformers==4.25.1
8
+ numpy==1.23.5
9
+ numba==0.56.4
10
+ datasets==2.8.0
11
+ librosa==0.9.2
12
+ numba==0.56.4
13
+ scikit-learn==1.3.2
14
+ ipdb>=0.13.9
15
+ pandas>=1.5.3
16
+ huggingface_hub>=0.7.0
17
+ hyperpyyaml>=0.0.1
18
+ joblib>=0.14.1
19
+ packaging
20
+ pre-commit>=2.3.0
21
+ sentencepiece>=0.1.91
22
+ psutil
23
+ SoundFile>=0.10.2
24
+ torch==1.11.0
25
+ torchaudio==0.11.0
26
+ torchvision== 0.12.0
27
+ tqdm>=4.42.0
28
+ yt-dlp
29
+ pydub
utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
utils/accent_analysis.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchaudio
3
+ import streamlit as st
4
+ import traceback
5
+ import psutil
6
+
7
+
8
+ # Accent label map
9
+ ACCENT_LABELS = {
10
+ "us": "American Accent",
11
+ "england": "British Accent",
12
+ "australia": "Australian Accent",
13
+ "indian": "Indian Accent",
14
+ "canada": "Canadian Accent",
15
+ "bermuda": "Bermudian Accent",
16
+ "scotland": "Scottish Accent",
17
+ "african": "African Accent",
18
+ "ireland": "Irish Accent",
19
+ "newzealand": "New Zealand Accent",
20
+ "wales": "Welsh Accent",
21
+ "malaysia": "Malaysian Accent",
22
+ "philippines": "Philippine Accent",
23
+ "singapore": "Singaporean Accent",
24
+ "hongkong": "Hong Kong Accent",
25
+ "southatlandtic": "South Atlantic Accent"
26
+ }
27
+
28
+ def analyze_accent(audio_tensor, sample_rate, model):
29
+ """Classifies audio to identify English accent."""
30
+ try:
31
+ # Convert stereo to mono (if needed)
32
+ if audio_tensor.shape[0] > 1:
33
+ audio_tensor = audio_tensor.mean(dim=0, keepdim=True)
34
+ audio_tensor = audio_tensor.squeeze(0).unsqueeze(0).to(torch.float32)
35
+
36
+ # Convert to 16kHz if needed
37
+ if sample_rate != 16000:
38
+ resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)
39
+ audio_tensor = resampler(audio_tensor)
40
+
41
+ audio_tensor = audio_tensor.to("cpu")
42
+ with torch.no_grad():
43
+ # Perform Classification
44
+ out_prob, score, index, text_lab = model.classify_batch(audio_tensor)
45
+ accent_label = text_lab[0]
46
+ readable = ACCENT_LABELS.get(accent_label, accent_label.title() + " accent")
47
+ return readable, round(score[0].item() * 100, 2)
48
+ except Exception:
49
+ st.error("❌ Error during classification.")
50
+ st.code(traceback.format_exc())
51
+ return None, None
utils/audio_processing.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import tempfile
3
+ import subprocess
4
+ import streamlit as st
5
+ from pydub import AudioSegment
6
+ import shutil
7
+
8
+ AudioSegment.converter = shutil.which("ffmpeg")
9
+
10
+ # -------------------------------
11
+ # Utility Function: Download audio from a Video url
12
+ # -------------------------------
13
+ def download_audio_as_wav(url, max_filesize_mb=70):
14
+ """
15
+ Downloads audio from a URL using yt-dlp, then converts it to WAV using ffmpeg.
16
+ Supports fallback formats (.m4a, .webm, .opus) if .mp3 not found.
17
+ Cleans up temporary files after use.
18
+ Returns path to .wav file or None on failure.
19
+ """
20
+ audio_path = None
21
+ temp_wav = None
22
+
23
+ try:
24
+ with tempfile.TemporaryDirectory() as temp_dir:
25
+ max_bytes = max_filesize_mb * 1024 * 1024
26
+ output_template = os.path.join(temp_dir, "audio.%(ext)s")
27
+
28
+ # yt-dlp download command
29
+ download_cmd = [
30
+ "yt-dlp",
31
+ "-f", f"bestaudio[filesize<={max_bytes}]",
32
+ "--extract-audio",
33
+ "--audio-format", "mp3",
34
+ "--no-playlist",
35
+ "--no-cache-dir",
36
+ "--restrict-filenames",
37
+ "-o", output_template,
38
+ url
39
+ ]
40
+
41
+ subprocess.run(download_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
42
+
43
+ # Try to locate audio file (mp3 or fallback)
44
+ common_exts = [".mp3", ".m4a", ".webm", ".opus"]
45
+ for ext in common_exts:
46
+ matches = [f for f in os.listdir(temp_dir) if f.endswith(ext)]
47
+ if matches:
48
+ audio_path = os.path.join(temp_dir, matches[0])
49
+ break
50
+
51
+ if not audio_path or not os.path.exists(audio_path):
52
+ st.error("❌ No supported audio file found after download.")
53
+ return None
54
+
55
+ # Convert to WAV (outside temp_dir so it persists)
56
+ temp_wav = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
57
+ convert_cmd = ["ffmpeg", "-y", "-i", audio_path, temp_wav.name]
58
+ subprocess.run(convert_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
59
+
60
+ # Return WAV file path; temp_dir and downloaded audio cleaned automatically
61
+ return temp_wav.name
62
+
63
+ except subprocess.CalledProcessError as e:
64
+ error_msg = e.stderr.decode() if hasattr(e, "stderr") else str(e)
65
+ if "st" in globals():
66
+ st.error("❌ Audio download or conversion failed.")
67
+ st.code(error_msg)
68
+ else:
69
+ print("Error during processing:", error_msg)
70
+ # Cleanup wav if created
71
+ if temp_wav is not None and os.path.exists(temp_wav.name):
72
+ os.remove(temp_wav.name)
73
+ return None
74
+
75
+ except Exception as e:
76
+ if "st" in globals():
77
+ st.error("❌ Unexpected error occurred.")
78
+ st.code(str(e))
79
+ else:
80
+ print("Unexpected error:", e)
81
+ if temp_wav is not None and os.path.exists(temp_wav.name):
82
+ os.remove(temp_wav.name)
83
+ return None
84
+
85
+ # --------------------------
86
+ # Utility: Trim audios to 2 minutes
87
+ # --------------------------
88
+ def trim_audio(input_wav_path, max_duration_sec=120):
89
+ """
90
+ Trims the input .wav file to the first `max_duration_sec` seconds.
91
+ Returns the path to the trimmed .wav file.
92
+ """
93
+ try:
94
+ # Load audio using pydub
95
+ audio = AudioSegment.from_wav(input_wav_path)
96
+
97
+ # Trim to max_duration_sec
98
+ trimmed_audio = audio[:max_duration_sec * 1000] # pydub uses milliseconds
99
+ # Save to a new temporary .wav file
100
+ trimmed_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
101
+ trimmed_audio.export(trimmed_file.name, format="wav")
102
+
103
+ return trimmed_file.name
104
+
105
+ except Exception as e:
106
+ st.error(f"❌ Error trimming audio: {e}")
107
+ if trimmed_file and os.path.exists(trimmed_file.name):
108
+ os.remove(trimmed_file.name)
109
+ return None
utils/session_utils.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import psutil
3
+
4
+ # -------------------------------
5
+ # Manage Station state variables
6
+ # -------------------------------
7
+
8
+ def initialize_session_state():
9
+ defaults = {
10
+ "audio_path": None,
11
+ "audio_ready": False,
12
+ "transcription": "",
13
+ }
14
+ for k, v in defaults.items():
15
+ if k not in st.session_state:
16
+ st.session_state[k] = v
17
+
18
+ # πŸ” Show memory info after
19
+ def display_memory_once():
20
+ if 'memory_logged' not in st.session_state:
21
+ mem = psutil.virtual_memory()
22
+ st.markdown(f"🧠 **Memory Used:** {mem.percent}%")
23
+ st.session_state.memory_logged = True
24
+
25
+ # Reset the app
26
+ def reset_session_state_except_model():
27
+ keys_to_keep = {"classifier", "whisper"}
28
+ for key in list(st.session_state.keys()):
29
+ if key not in keys_to_keep:
30
+ del st.session_state[key]
utils/video_processing.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import subprocess
3
+ import os
4
+ from moviepy.editor import VideoFileClip
5
+ import streamlit as st
6
+ import traceback
7
+ import shutil
8
+
9
+
10
+ # --------------------------
11
+ # Utility: Trim videos to 2 minutes
12
+ # --------------------------
13
+ def trim_video(video_path, max_duration=120):
14
+ """Trims video to max_duration (in seconds) and extracts audio."""
15
+ try:
16
+ video = VideoFileClip(video_path)
17
+ duration = video.duration
18
+ video.close()
19
+
20
+ audio_path = tempfile.NamedTemporaryFile(delete=False, suffix=".wav").name
21
+ command = [
22
+ "ffmpeg", "-i", video_path,
23
+ "-t", str(min(duration, max_duration)),
24
+ "-ar", "16000", "-ac", "1",
25
+ "-acodec", "pcm_s16le", "-y", audio_path
26
+ ]
27
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
28
+ if result.returncode != 0:
29
+ st.error("❌ ffmpeg audio extraction failed.")
30
+ os.remove(audio_path) # Clean up failed temp file
31
+ st.code(result.stderr.decode())
32
+ return None
33
+
34
+ return audio_path
35
+ except Exception as e:
36
+ st.error(f"❌ Error trimming video: {e}")
37
+ os.remove(audio_path)
38
+ st.code(traceback.format_exc())
39
+ return None
40
+
41
+ finally:
42
+ # Clean up input video if it was a temp file
43
+ if "tmp" in video_path and os.path.exists(video_path):
44
+ try:
45
+ os.remove(video_path)
46
+ except Exception:
47
+ pass # Avoid crashing on cleanup