speech-test commited on
Commit
cfbc0a5
1 Parent(s): f3122f0
Files changed (1) hide show
  1. app.py +105 -0
app.py CHANGED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+
3
+ import streamlit as st
4
+ import torch
5
+ from streamlit_player import st_player
6
+ from transformers import AutoModelForCTC, Wav2Vec2Processor
7
+
8
+ from streaming import ffmpeg_stream
9
+
10
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
11
+ player_options = {
12
+ "events": ["onProgress"],
13
+ "progress_interval": 200,
14
+ "volume": 1.0,
15
+ "playing": True,
16
+ "loop": False,
17
+ "controls": False,
18
+ "muted": False,
19
+ "config": {"youtube": {"playerVars": {"start": 1}}},
20
+ }
21
+
22
+
23
+ @st.cache(hash_funcs={torch.nn.parameter.Parameter: lambda _: None})
24
+ def load_model(model_path="facebook/wav2vec2-large-robust-ft-swbd-300h"):
25
+ processor = Wav2Vec2Processor.from_pretrained(model_path)
26
+ model = AutoModelForCTC.from_pretrained(model_path).to(device)
27
+ return processor, model
28
+
29
+
30
+ processor, model = load_model()
31
+
32
+
33
+ def stream_text(url, chunk_duration_ms, pad_duration_ms):
34
+ sampling_rate = processor.feature_extractor.sampling_rate
35
+
36
+ # calculate the length of logits to cut from the sides of the output to account for input padding
37
+ output_pad_len = model._get_feat_extract_output_lengths(int(sampling_rate * pad_duration_ms / 1000))
38
+
39
+ # define the audio chunk generator
40
+ stream = ffmpeg_stream(url, sampling_rate, chunk_duration_ms=chunk_duration_ms, pad_duration_ms=pad_duration_ms)
41
+
42
+ leftover_text = ""
43
+ for i, chunk in enumerate(stream):
44
+ input_values = processor(chunk, sampling_rate=sampling_rate, return_tensors="pt").input_values
45
+
46
+ with torch.no_grad():
47
+ logits = model(input_values.to(device)).logits[0]
48
+ if i > 0:
49
+ logits = logits[output_pad_len : len(logits) - output_pad_len]
50
+ else: # don't count padding at the start of the clip
51
+ logits = logits[: len(logits) - output_pad_len]
52
+
53
+ predicted_ids = torch.argmax(logits, dim=-1).cpu().tolist()
54
+ if processor.decode(predicted_ids).strip():
55
+ leftover_ids = processor.tokenizer.encode(leftover_text)
56
+ # concat the last word (or its part) from the last frame with the current text
57
+ text = processor.decode(leftover_ids + predicted_ids)
58
+ # don't return the last word in case it's just partially recognized
59
+ text, leftover_text = text.rsplit(" ", 1)
60
+ yield text
61
+ else:
62
+ yield leftover_text
63
+ leftover_text = ""
64
+
65
+ yield leftover_text
66
+
67
+
68
+ def main():
69
+ state = st.session_state
70
+ st.header("YouTube Streaming ASR with Robust Wav2Vec2")
71
+
72
+ with st.form(key="inputs_form"):
73
+ state.youtube_url = st.text_input("YouTube URL", "https://www.youtube.com/watch?v=yJmiZ1Mo1cQ")
74
+ state.chunk_duration_ms = st.slider("Audio chunk duration (ms)", 2000, 10000, 3000, 100)
75
+ state.pad_duration_ms = st.slider("Padding duration (ms)", 100, 5000, 1000, 100)
76
+ submit_button = st.form_submit_button(label="Submit")
77
+
78
+ if submit_button or "asr_stream" not in state:
79
+ # a hack to update the video player on value changes
80
+ state.youtube_url = (
81
+ state.youtube_url.split("&hash=")[0]
82
+ + f"&hash={state.chunk_duration_ms}-{state.pad_duration_ms}"
83
+ )
84
+ state.asr_stream = stream_text(
85
+ state.youtube_url, state.chunk_duration_ms, state.pad_duration_ms
86
+ )
87
+ state.chunks_taken = 0
88
+ state.lines = deque([], maxlen=3) # limit to the last 3 lines of subs
89
+
90
+ player = st_player(state.youtube_url, **player_options, key="youtube_player")
91
+
92
+ if "asr_stream" in state and player.data and player.data["played"] < 1.0:
93
+ # check how many seconds were played, and if more than processed - write the next text chunk
94
+ processed_seconds = state.chunks_taken * (state.chunk_duration_ms / 1000)
95
+ if processed_seconds < player.data["playedSeconds"]:
96
+ text = next(state.asr_stream)
97
+ state.lines.append(text)
98
+ state.chunks_taken += 1
99
+ if "lines" in state:
100
+ # print the last 3 lines of subs
101
+ st.code("\n".join(state.lines))
102
+
103
+
104
+ if __name__ == "__main__":
105
+ main()