asahi417 commited on
Commit
69bc1a2
β€’
1 Parent(s): 7088ba0

add stability ts

Browse files
Files changed (2) hide show
  1. app.py +120 -17
  2. requirements.txt +2 -1
app.py CHANGED
@@ -2,14 +2,16 @@ import os
2
  import time
3
  import tempfile
4
  from math import floor
5
- from typing import Optional
6
 
7
  import torch
8
  import gradio as gr
9
  import yt_dlp as youtube_dl
 
10
  from transformers import pipeline
11
  from transformers.pipelines.audio_utils import ffmpeg_read
12
  from punctuators.models import PunctCapSegModelONNX
 
13
 
14
 
15
  # configuration
@@ -18,7 +20,6 @@ BATCH_SIZE = 16
18
  CHUNK_LENGTH_S = 15
19
  FILE_LIMIT_MB = 1000
20
  YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
21
- PUNCTUATOR = PunctCapSegModelONNX.from_pretrained("pcs_47lang")
22
 
23
 
24
  # device setting
@@ -43,6 +44,104 @@ pipe = pipeline(
43
  )
44
 
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  def format_time(start: Optional[float], end: Optional[float]):
47
 
48
  def _format_time(seconds: Optional[float]):
@@ -58,19 +157,18 @@ def format_time(start: Optional[float], end: Optional[float]):
58
  return f"[{_format_time(start)}-> {_format_time(end)}]:"
59
 
60
 
61
- def get_prediction(inputs, prompt: Optional[str], punctuate_text: bool = True):
62
  generate_kwargs = {"language": "japanese", "task": "transcribe"}
63
  if prompt:
64
  generate_kwargs['prompt_ids'] = pipe.tokenizer.get_prompt_ids(prompt, return_tensors='pt').to(device)
65
  prediction = pipe(inputs, return_timestamps=True, generate_kwargs=generate_kwargs)
 
 
 
 
 
66
  if punctuate_text:
67
- text_edit = PUNCTUATOR.infer([c['text'] for c in prediction['chunks']])
68
- prediction['chunks'] = [
69
- {
70
- 'timestamp': c['timestamp'],
71
- 'text': "".join(e) if 'unk' not in "".join(e).lower() else c['text']
72
- } for c, e in zip(prediction['chunks'], text_edit)
73
- ]
74
  text = "".join([c['text'] for c in prediction['chunks']])
75
  text_timestamped = "\n".join([
76
  f"{format_time(*c['timestamp'])} {c['text']}" for c in prediction['chunks']
@@ -78,10 +176,12 @@ def get_prediction(inputs, prompt: Optional[str], punctuate_text: bool = True):
78
  return text, text_timestamped
79
 
80
 
81
- def transcribe(inputs, prompt, punctuate_text: bool = True):
82
  if inputs is None:
83
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
84
- return get_prediction(inputs, prompt, punctuate_text)
 
 
85
 
86
 
87
  def _return_yt_html_embed(yt_url):
@@ -115,7 +215,7 @@ def download_yt_audio(yt_url, filename):
115
  raise gr.Error(str(err))
116
 
117
 
118
- def yt_transcribe(yt_url, prompt, punctuate_text: bool = True):
119
  html_embed_str = _return_yt_html_embed(yt_url)
120
  with tempfile.TemporaryDirectory() as tmpdirname:
121
  filepath = os.path.join(tmpdirname, "video.mp4")
@@ -124,7 +224,7 @@ def yt_transcribe(yt_url, prompt, punctuate_text: bool = True):
124
  inputs = f.read()
125
  inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
126
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
127
- text, text_timestamped = get_prediction(inputs, prompt, punctuate_text)
128
  return html_embed_str, text, text_timestamped
129
 
130
 
@@ -134,7 +234,8 @@ mf_transcribe = gr.Interface(
134
  inputs=[
135
  gr.inputs.Audio(source="microphone", type="filepath", optional=True),
136
  gr.inputs.Textbox(lines=1, placeholder="Prompt", optional=True),
137
- gr.inputs.Checkbox(default=True, label="Add punctuations")
 
138
  ],
139
  outputs=["text", "text"],
140
  layout="horizontal",
@@ -149,7 +250,8 @@ file_transcribe = gr.Interface(
149
  inputs=[
150
  gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
151
  gr.inputs.Textbox(lines=1, placeholder="Prompt", optional=True),
152
- gr.inputs.Checkbox(default=True, label="Add punctuations")
 
153
  ],
154
  outputs=["text", "text"],
155
  layout="horizontal",
@@ -163,7 +265,8 @@ yt_transcribe = gr.Interface(
163
  inputs=[
164
  gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
165
  gr.inputs.Textbox(lines=1, placeholder="Prompt", optional=True),
166
- gr.inputs.Checkbox(default=True, label="Add punctuations")
 
167
  ],
168
  outputs=["html", "text", "text"],
169
  layout="horizontal",
 
2
  import time
3
  import tempfile
4
  from math import floor
5
+ from typing import Optional, List, Dict, Any
6
 
7
  import torch
8
  import gradio as gr
9
  import yt_dlp as youtube_dl
10
+ import numpy as np
11
  from transformers import pipeline
12
  from transformers.pipelines.audio_utils import ffmpeg_read
13
  from punctuators.models import PunctCapSegModelONNX
14
+ from stable_whisper import WhisperResult
15
 
16
 
17
  # configuration
 
20
  CHUNK_LENGTH_S = 15
21
  FILE_LIMIT_MB = 1000
22
  YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
 
23
 
24
 
25
  # device setting
 
44
  )
45
 
46
 
47
+ class Punctuator:
48
+
49
+ ja_punctuations = ["!", "?", "、", "。"]
50
+
51
+ def __init__(self, model: str = "pcs_47lang"):
52
+ self.punctuation_model = PunctCapSegModelONNX.from_pretrained(model)
53
+
54
+ def punctuate(self, pipeline_chunk: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
55
+
56
+ def validate_punctuation(raw: str, punctuated: str):
57
+ if 'unk' in punctuated:
58
+ return raw
59
+ if punctuated.count("。") > 1:
60
+ ind = punctuated.rfind("。")
61
+ punctuated = punctuated.replace("。", "")
62
+ punctuated = punctuated[:ind] + "。" + punctuated[ind:]
63
+ return punctuated
64
+
65
+ text_edit = self.punctuation_model.infer([c['text'] for c in pipeline_chunk])
66
+ return [
67
+ {
68
+ 'timestamp': c['timestamp'],
69
+ 'text': validate_punctuation(c['text'], "".join(e))
70
+ } for c, e in zip(pipeline_chunk, text_edit)
71
+ ]
72
+
73
+
74
+ PUNCTUATOR = Punctuator()
75
+
76
+
77
+ def _fix_timestamp(sample_rate: int, result: List[Dict[str, Any]], audio: np.ndarray) -> WhisperResult or None:
78
+
79
+ def replace_none_ts(parts):
80
+ total_dur = round(audio.shape[-1] / sample_rate, 3)
81
+ _medium_dur = _ts_nonzero_mask = None
82
+
83
+ def ts_nonzero_mask() -> np.ndarray:
84
+ nonlocal _ts_nonzero_mask
85
+ if _ts_nonzero_mask is None:
86
+ _ts_nonzero_mask = np.array([(p['end'] or p['start']) is not None for p in parts])
87
+ return _ts_nonzero_mask
88
+
89
+ def medium_dur() -> float:
90
+ nonlocal _medium_dur
91
+ if _medium_dur is None:
92
+ nonzero_dus = [p['end'] - p['start'] for p in parts if None not in (p['end'], p['start'])]
93
+ nonzero_durs = np.array(nonzero_dus)
94
+ _medium_dur = np.median(nonzero_durs) * 2 if len(nonzero_durs) else 2.0
95
+ return _medium_dur
96
+
97
+ def _curr_max_end(start: float, next_idx: float) -> float:
98
+ max_end = total_dur
99
+ if next_idx != len(parts):
100
+ mask = np.flatnonzero(ts_nonzero_mask()[next_idx:])
101
+ if len(mask):
102
+ _part = parts[mask[0]+next_idx]
103
+ max_end = _part['start'] or _part['end']
104
+
105
+ new_end = round(start + medium_dur(), 3)
106
+ if new_end > max_end:
107
+ return max_end
108
+ return new_end
109
+
110
+ for i, part in enumerate(parts, 1):
111
+ if part['start'] is None:
112
+ is_first = i == 1
113
+ if is_first:
114
+ new_start = round((part['end'] or 0) - medium_dur(), 3)
115
+ part['start'] = max(new_start, 0.0)
116
+ else:
117
+ part['start'] = parts[i - 2]['end']
118
+ if part['end'] is None:
119
+ no_next_start = i == len(parts) or parts[i]['start'] is None
120
+ part['end'] = _curr_max_end(part['start'], i) if no_next_start else parts[i]['start']
121
+
122
+ words = [dict(start=word['timestamp'][0], end=word['timestamp'][1], word=word['text']) for word in result]
123
+ replace_none_ts(words)
124
+ return WhisperResult([words], force_order=True, check_sorted=True)
125
+
126
+
127
+ def fix_timestamp(pipeline_output: List[Dict[str, Any]], audio: np.ndarray, sample_rate: int) -> List[Dict[str, Any]]:
128
+ result = _fix_timestamp(sample_rate=sample_rate, audio=audio, result=pipeline_output)
129
+ result.adjust_by_silence(
130
+ audio,
131
+ q_levels=20,
132
+ k_size=5,
133
+ sample_rate=sample_rate,
134
+ min_word_dur=None,
135
+ word_level=True,
136
+ verbose=True,
137
+ nonspeech_error=0.1,
138
+ use_word_position=True
139
+ )
140
+ if result.has_words:
141
+ result.regroup(True)
142
+ return [{"timestamp": [s.start, s.end], "text": s.text} for s in result.segments]
143
+
144
+
145
  def format_time(start: Optional[float], end: Optional[float]):
146
 
147
  def _format_time(seconds: Optional[float]):
 
157
  return f"[{_format_time(start)}-> {_format_time(end)}]:"
158
 
159
 
160
+ def get_prediction(inputs, prompt: Optional[str], punctuate_text: bool = True, stabilize_timestamp: bool = True):
161
  generate_kwargs = {"language": "japanese", "task": "transcribe"}
162
  if prompt:
163
  generate_kwargs['prompt_ids'] = pipe.tokenizer.get_prompt_ids(prompt, return_tensors='pt').to(device)
164
  prediction = pipe(inputs, return_timestamps=True, generate_kwargs=generate_kwargs)
165
+ if stabilize_timestamp:
166
+ prediction['chunks'] = fix_timestamp(pipeline_output=prediction['chunks'],
167
+ audio=inputs["array"],
168
+ sample_rate=inputs["sampling_rate"]
169
+ )
170
  if punctuate_text:
171
+ prediction['chunks'] = PUNCTUATOR.punctuate(prediction['chunks'])
 
 
 
 
 
 
172
  text = "".join([c['text'] for c in prediction['chunks']])
173
  text_timestamped = "\n".join([
174
  f"{format_time(*c['timestamp'])} {c['text']}" for c in prediction['chunks']
 
176
  return text, text_timestamped
177
 
178
 
179
+ def transcribe(inputs, prompt, punctuate_text, stabilize_timestamp):
180
  if inputs is None:
181
  raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
182
+ inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
183
+ inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
184
+ return get_prediction(inputs, prompt, punctuate_text, stabilize_timestamp)
185
 
186
 
187
  def _return_yt_html_embed(yt_url):
 
215
  raise gr.Error(str(err))
216
 
217
 
218
+ def yt_transcribe(yt_url, prompt, punctuate_text: bool = True, stabilize_timestamp: bool = True):
219
  html_embed_str = _return_yt_html_embed(yt_url)
220
  with tempfile.TemporaryDirectory() as tmpdirname:
221
  filepath = os.path.join(tmpdirname, "video.mp4")
 
224
  inputs = f.read()
225
  inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate)
226
  inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
227
+ text, text_timestamped = get_prediction(inputs, prompt, punctuate_text, stabilize_timestamp)
228
  return html_embed_str, text, text_timestamped
229
 
230
 
 
234
  inputs=[
235
  gr.inputs.Audio(source="microphone", type="filepath", optional=True),
236
  gr.inputs.Textbox(lines=1, placeholder="Prompt", optional=True),
237
+ gr.inputs.Checkbox(default=True, label="Add punctuations"),
238
+ gr.inputs.Checkbox(default=True, label="Stabilize timestamp")
239
  ],
240
  outputs=["text", "text"],
241
  layout="horizontal",
 
250
  inputs=[
251
  gr.inputs.Audio(source="upload", type="filepath", optional=True, label="Audio file"),
252
  gr.inputs.Textbox(lines=1, placeholder="Prompt", optional=True),
253
+ gr.inputs.Checkbox(default=True, label="Add punctuations"),
254
+ gr.inputs.Checkbox(default=True, label="Stabilize timestamp")
255
  ],
256
  outputs=["text", "text"],
257
  layout="horizontal",
 
265
  inputs=[
266
  gr.inputs.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"),
267
  gr.inputs.Textbox(lines=1, placeholder="Prompt", optional=True),
268
+ gr.inputs.Checkbox(default=True, label="Add punctuations"),
269
+ gr.inputs.Checkbox(default=True, label="Stabilize timestamp")
270
  ],
271
  outputs=["html", "text", "text"],
272
  layout="horizontal",
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  git+https://github.com/huggingface/transformers
2
  torch
3
  yt-dlp
4
- punctuators
 
 
1
  git+https://github.com/huggingface/transformers
2
  torch
3
  yt-dlp
4
+ punctuators==0.0.5
5
+ stable_whisper==2.16.0