raffel-22 commited on
Commit
b8a2d43
·
verified ·
1 Parent(s): 9fee032

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +169 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,171 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import os
3
+ import tempfile
4
+ import torch
5
+ import json
6
+ import urllib.request
7
+ from urllib.parse import urlparse
8
+ from moviepy import VideoFileClip, AudioFileClip
9
+ from speechbrain.pretrained.interfaces import foreign_class
10
+ import yt_dlp
11
+ from pydub import AudioSegment
12
+ from pydub.silence import detect_nonsilent
13
 
14
+ # Load model once
15
+ classifier = foreign_class(
16
+ source="Jzuluaga/accent-id-commonaccent_xlsr-en-english",
17
+ pymodule_file="custom_interface.py",
18
+ classname="CustomEncoderWav2vec2Classifier"
19
+ )
20
+
21
+ def extract_loom_id(url):
22
+ parsed_url = urlparse(url)
23
+ return parsed_url.path.split("/")[-1]
24
+
25
+ def download_loom_video(url, filename):
26
+ try:
27
+ video_id = extract_loom_id(url)
28
+ request = urllib.request.Request(
29
+ url=f"https://www.loom.com/api/campaigns/sessions/{video_id}/transcoded-url",
30
+ headers={},
31
+ method="POST"
32
+ )
33
+ response = urllib.request.urlopen(request)
34
+ body = response.read()
35
+ content = json.loads(body.decode("utf-8"))
36
+ video_url = content["url"]
37
+ urllib.request.urlretrieve(video_url, filename)
38
+ return filename
39
+ except Exception as e:
40
+ raise RuntimeError(f"Failed to download video from Loom: {e}")
41
+
42
+ def download_youtube_audio(url):
43
+ try:
44
+ ydl_opts = {
45
+ 'format': 'bestaudio/best',
46
+ 'outtmpl': 'yt_audio.%(ext)s',
47
+ 'quiet': True,
48
+ 'postprocessors': [{
49
+ 'key': 'FFmpegExtractAudio',
50
+ 'preferredcodec': 'mp3',
51
+ 'preferredquality': '64',
52
+ }],
53
+ }
54
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
55
+ ydl.download([url])
56
+
57
+ audioclip = AudioFileClip("yt_audio.mp3")
58
+ wav_path = "output.wav"
59
+ audioclip.write_audiofile(wav_path, logger=None)
60
+ audioclip.close()
61
+ os.remove("yt_audio.mp3")
62
+ return wav_path
63
+ except Exception as e:
64
+ raise RuntimeError(f"Failed to download from YouTube: {e}")
65
+
66
+ def download_direct_video(url):
67
+ try:
68
+ response = urllib.request.urlopen(url)
69
+ if response.status != 200:
70
+ raise RuntimeError("Failed to download video.")
71
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_file:
72
+ temp_file.write(response.read())
73
+ return temp_file.name
74
+ except Exception as e:
75
+ raise RuntimeError(f"Failed to download video : {e}")
76
+
77
+ def extract_audio(video_path):
78
+ try:
79
+ clip = VideoFileClip(video_path)
80
+ # audio_clip = clip.audio.subclip(0, min(duration, clip.duration)) # ambil 10 detik awal atau durasi video kalau kurang
81
+ wav_path = video_path.replace(".mp4", ".wav")
82
+ clip.audio.write_audiofile(wav_path)
83
+ return wav_path
84
+ except Exception as e:
85
+ raise RuntimeError(f"Fail to extract the video : {e}")
86
+
87
+ def get_speech_segments(audio_path, min_silence_len=700, silence_thresh=-40, duration=10000):
88
+ """
89
+ Get speech segments with absolute position
90
+ Detects non-silent parts in audio with precise timing
91
+ """
92
+ audio = AudioSegment.from_wav(audio_path)
93
+ total_duration = len(audio)
94
+
95
+ nonsilent_ranges = detect_nonsilent(
96
+ audio,
97
+ min_silence_len=min_silence_len,
98
+ silence_thresh=silence_thresh
99
+ )
100
+
101
+ start_ms, original_end_ms = nonsilent_ranges[0]
102
+ end_ms = min(start_ms + duration, total_duration)
103
+
104
+ segment = audio[start_ms:end_ms]
105
+ temp_path = "temp_first_segment.wav"
106
+ segment.export(temp_path, format="wav")
107
+
108
+ return temp_path
109
+
110
+ def classify_audio(wav_path):
111
+ out_prob, score, index, label = classifier.classify_file(get_speech_segments(wav_path))
112
+ confidence = float(score[0]) * 100 # convert tensor to float
113
+ return label, confidence
114
+
115
+ def delete_file(path):
116
+ try:
117
+ os.remove(path)
118
+ except:
119
+ pass
120
+
121
+ # Streamlit UI
122
+ st.title("Accent Classifier for English Speakers")
123
+
124
+ with st.form("Input your video (it can be video link or upload)"):
125
+ video_url = st.text_input(
126
+ "Enter video URL (YouTube, Loom, or .mp4)"
127
+ )
128
+
129
+ uploaded_file = st.file_uploader(
130
+ "Or upload a video file (mp4, mov, or mkv)",
131
+ type=["mp4", "mov", "avi"]
132
+ )
133
+
134
+ if st.form_submit_button("Process"):
135
+ video_path = None
136
+ wav_path = None
137
+
138
+ try:
139
+ with st.spinner('Processing video... Please wait'):
140
+ if video_url:
141
+ if "youtube.com" in video_url or "youtu.be" in video_url:
142
+ wav_path = download_youtube_audio(video_url)
143
+ elif "loom.com" in video_url:
144
+ video_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
145
+ download_loom_video(video_url, video_path)
146
+ wav_path = extract_audio(video_path)
147
+ elif video_url.endswith(".mp4"):
148
+ video_path = download_direct_video(video_url)
149
+ wav_path = extract_audio(video_path)
150
+ else:
151
+ st.error("URL Format unrecognized.")
152
+ elif uploaded_file is not None:
153
+ video_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
154
+ with open(video_path, "wb") as f:
155
+ f.write(uploaded_file.read())
156
+ wav_path = extract_audio(video_path)
157
+ else:
158
+ st.error("Please upload a file or link")
159
+
160
+ if wav_path:
161
+ label, confidence = classify_audio(wav_path)
162
+ st.success(f"Video Accent: **{label}**")
163
+ st.info(f"Confidence Score: **{confidence:.2f}%**")
164
+ else:
165
+ st.error("Error processing video")
166
+
167
+ except Exception as e:
168
+ st.error(str(e))
169
+ finally:
170
+ delete_file(wav_path)
171
+ delete_file(video_path)