AshDavid12 commited on
Commit
2417517
·
1 Parent(s): 0002733

trying to build docker image w files

Browse files
Files changed (6) hide show
  1. .DS_Store +0 -0
  2. .idea/ivrit-ai-streaming.iml +1 -1
  3. infer.py +201 -0
  4. pyproject.toml +32 -0
  5. requirements.txt +5 -0
  6. whisper_online.py +890 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.idea/ivrit-ai-streaming.iml CHANGED
@@ -2,7 +2,7 @@
2
  <module type="PYTHON_MODULE" version="4">
3
  <component name="NewModuleRootManager">
4
  <content url="file://$MODULE_DIR$" />
5
- <orderEntry type="inheritedJdk" />
6
  <orderEntry type="sourceFolder" forTests="false" />
7
  </component>
8
  </module>
 
2
  <module type="PYTHON_MODULE" version="4">
3
  <component name="NewModuleRootManager">
4
  <content url="file://$MODULE_DIR$" />
5
+ <orderEntry type="jdk" jdkName="Poetry (ivrit-ai-streaming)" jdkType="Python SDK" />
6
  <orderEntry type="sourceFolder" forTests="false" />
7
  </component>
8
  </module>
infer.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import runpod
2
+
3
+ import base64
4
+ import faster_whisper
5
+ import tempfile
6
+ import logging
7
+ import torch
8
+ import sys
9
+ import requests
10
+
11
+ import whisper_online
12
+
13
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',
14
+ handlers=[logging.StreamHandler(sys.stdout)])
15
+
16
+ # Try to import the module
17
+ try:
18
+ logging.info("attempting to load whisper online")
19
+ from whisper_online import * # Replace 'some_module' with the actual module name
20
+
21
+ logging.info("Successfully imported whisper_online.")
22
+ except ImportError as e:
23
+ logging.error(f"Failed to import whisper_online: {e}", exc_info=True)
24
+ except Exception as e:
25
+ logging.error(f"Unknown from exception- error to import whisper_online: {e}", exc_info=True)
26
+
27
+ if torch.cuda.is_available():
28
+ logging.info(f"CUDA is available.")
29
+ else:
30
+ logging.info("CUDA is not available. Using CPU.")
31
+
32
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
33
+
34
+ model_name = 'ivrit-ai/faster-whisper-v2-d3-e3'
35
+ logging.info(f"Selected model name: {model_name}")
36
+ #model = faster_whisper.WhisperModel(model_name, device=device)
37
+ try:
38
+ lan = 'he'
39
+ logging.info(f"Attempting to initialize FasterWhisperASR with device: {device}")
40
+ model = whisper_online.FasterWhisperASR(lan=lan, modelsize=model_name, cache_dir=None, model_dir=None)
41
+ logging.info("FasterWhisperASR model initialized successfully.")
42
+ except Exception as e:
43
+ logging.error(f"Falied to inilialize faster whisper model {e}")
44
+
45
+ # Maximum data size: 200MB
46
+ MAX_PAYLOAD_SIZE = 200 * 1024 * 1024
47
+
48
+
49
+ def download_file(url, max_size_bytes, output_filename, api_key=None):
50
+ """
51
+ Download a file from a given URL with size limit and optional API key.
52
+
53
+ Args:
54
+ url (str): The URL of the file to download.
55
+ max_size_bytes (int): Maximum allowed file size in bytes.
56
+ output_filename (str): The name of the file to save the download as.
57
+ api_key (str, optional): API key to be used as a bearer token.
58
+
59
+ Returns:
60
+ bool: True if download was successful, False otherwise.
61
+ """
62
+ try:
63
+ # Prepare headers
64
+ headers = {}
65
+ if api_key:
66
+ headers['Authorization'] = f'Bearer {api_key}'
67
+
68
+ # Send a GET request
69
+ response = requests.get(url, stream=True, headers=headers)
70
+ response.raise_for_status() # Raises an HTTPError for bad requests
71
+
72
+ # Get the file size if possible
73
+ file_size = int(response.headers.get('Content-Length', 0))
74
+
75
+ if file_size > max_size_bytes:
76
+ print(f"File size ({file_size} bytes) exceeds the maximum allowed size ({max_size_bytes} bytes).")
77
+ return False
78
+
79
+ # Download and write the file
80
+ downloaded_size = 0
81
+ with open(output_filename, 'wb') as file:
82
+ for chunk in response.iter_content(chunk_size=8192):
83
+ downloaded_size += len(chunk)
84
+ if downloaded_size > max_size_bytes:
85
+ print(f"Download stopped: Size limit exceeded ({max_size_bytes} bytes).")
86
+ return False
87
+ file.write(chunk)
88
+
89
+ print(f"File downloaded successfully: {output_filename}")
90
+ return True
91
+
92
+ except requests.RequestException as e:
93
+ print(f"Error downloading file: {e}")
94
+ return False
95
+
96
+
97
+ def transcribe(job):
98
+ datatype = job['input'].get('type', None)
99
+ if not datatype:
100
+ return {"error": "datatype field not provided. Should be 'blob' or 'url'."}
101
+
102
+ if not datatype in ['blob', 'url']:
103
+ return {"error": f"datatype should be 'blob' or 'url', but is {datatype} instead."}
104
+
105
+ # Get the API key from the job input
106
+ api_key = job['input'].get('api_key', None)
107
+
108
+ with tempfile.TemporaryDirectory() as d:
109
+ audio_file = f'{d}/audio.mp3'
110
+
111
+ if datatype == 'blob':
112
+ mp3_bytes = base64.b64decode(job['input']['data'])
113
+ open(audio_file, 'wb').write(mp3_bytes)
114
+ elif datatype == 'url':
115
+ success = download_file(job['input']['url'], MAX_PAYLOAD_SIZE, audio_file, api_key)
116
+ if not success:
117
+ return {"error": f"Error downloading data from {job['input']['url']}"}
118
+
119
+ result = transcribe_core(audio_file)
120
+ return {'result': result}
121
+
122
+
123
+ def transcribe_core(audio_file):
124
+ print('Transcribing...')
125
+
126
+ ret = {'segments': []}
127
+
128
+ segs, dummy = model.transcribe(audio_file, language='he', word_timestamps=True)
129
+ for s in segs:
130
+ words = []
131
+ for w in s.words:
132
+ words.append({'start': w.start, 'end': w.end, 'word': w.word, 'probability': w.probability})
133
+
134
+ seg = {'id': s.id, 'seek': s.seek, 'start': s.start, 'end': s.end, 'text': s.text, 'avg_logprob': s.avg_logprob,
135
+ 'compression_ratio': s.compression_ratio, 'no_speech_prob': s.no_speech_prob, 'words': words}
136
+
137
+ print(seg)
138
+ ret['segments'].append(seg)
139
+
140
+ return ret
141
+
142
+
143
+ #runpod.serverless.start({"handler": transcribe})
144
+
145
+ def transcribe_whisper(job):
146
+ logging.info(f"in triscribe-whisper")
147
+ datatype = job['input'].get('type', None)
148
+ if not datatype:
149
+ return {"error": "datatype field not provided. Should be 'blob' or 'url'."}
150
+
151
+ if not datatype in ['blob', 'url']:
152
+ return {"error": f"datatype should be 'blob' or 'url', but is {datatype} instead."}
153
+
154
+ # Get the API key from the job input
155
+ api_key = job['input'].get('api_key', None)
156
+
157
+ with tempfile.TemporaryDirectory() as d:
158
+ audio_file = f'{d}/audio.mp3'
159
+
160
+ if datatype == 'blob':
161
+ mp3_bytes = base64.b64decode(job['input']['data'])
162
+ open(audio_file, 'wb').write(mp3_bytes)
163
+ elif datatype == 'url':
164
+ success = download_file(job['input']['url'], MAX_PAYLOAD_SIZE, audio_file, api_key)
165
+ if not success:
166
+ return {"error": f"Error downloading data from {job['input']['url']}"}
167
+ logging.info("Starting transcription process using transcribe_core_whisper.")
168
+ result = transcribe_core_whisper(audio_file)
169
+ logging.info(f"DONE: in triscribe-whisper")
170
+ return {'result': result}
171
+
172
+ def transcribe_core_whisper(audio_file):
173
+ print('Transcribing...')
174
+
175
+ ret = {'segments': []}
176
+
177
+ try:
178
+ logging.debug(f"Transcribing audio file: {audio_file}")
179
+
180
+ segs = model.transcribe(audio_file, init_prompt="")
181
+ logging.info("Transcription completed successfully.")
182
+ for s in segs:
183
+ words = []
184
+ for w in s.words:
185
+ words.append({'start': w.start, 'end': w.end, 'word': w.word, 'probability': w.probability})
186
+
187
+ seg = {'id': s.id, 'seek': s.seek, 'start': s.start, 'end': s.end, 'text': s.text, 'avg_logprob': s.avg_logprob,
188
+ 'compression_ratio': s.compression_ratio, 'no_speech_prob': s.no_speech_prob, 'words': words}
189
+ logging.debug(f"All segments processed. Final transcription result: {ret}")
190
+ print(seg)
191
+ ret['segments'].append(seg)
192
+
193
+ except Exception as e:
194
+ # Log any exception that occurs during the transcription process
195
+ logging.error(f"Error during transcribe_core_whisper: {e}", exc_info=True)
196
+ return {"error": str(e)}
197
+ # Return the final result
198
+ logging.info("Transcription core function completed.")
199
+ return ret
200
+
201
+ runpod.serverless.start({"handler": transcribe_whisper})
pyproject.toml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "ivrit-streaming-gigaverse"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["AshDavid12 <gaashdavid@gmail.com>"]
6
+
7
+ [tool.poetry.dependencies]
8
+ python = "3.9.1"
9
+ pytube = "^15.0.0"
10
+ pydantic = "^2.8.2"
11
+ python-dotenv = "^1.0.1"
12
+ fastapi = "^0.111.1"
13
+ requests = "^2.32.3"
14
+ httpx = "^0.27.0"
15
+ uvicorn = "^0.30.1"
16
+ asyncio = "^3.4.3"
17
+ confluent-kafka = "^2.5.0"
18
+ flask = "^3.0.3"
19
+ faster-whisper = "1.0.3"
20
+ runpod = "^1.7.0"
21
+ librosa = ">=0.10.2.post1,<0.11.0"
22
+ soundfile = "^0.12.1"
23
+ openai = "^1.42.0"
24
+ numpy = "^1.22.0"
25
+ torch = "2.1.0"
26
+
27
+
28
+
29
+
30
+ [build-system]
31
+ requires = ["poetry-core"]
32
+ build-backend = "poetry.core.masonry.api"
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ numpy
2
+ librosa
3
+ runpod
4
+ faster-whisper
5
+ torch==2.3.1
whisper_online.py ADDED
@@ -0,0 +1,890 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import sys
3
+ import numpy as np
4
+ import librosa
5
+ from functools import lru_cache
6
+ import time
7
+ import logging
8
+
9
+ import io
10
+ import soundfile as sf
11
+ import math
12
+
13
+ logger = logging.getLogger(__name__)
14
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler(sys.stdout)])
15
+
16
+
17
+ @lru_cache
18
+ def load_audio(fname):
19
+ a, _ = librosa.load(fname, sr=16000, dtype=np.float32)
20
+ return a
21
+
22
+
23
+ def load_audio_chunk(fname, beg, end):
24
+ audio = load_audio(fname)
25
+ beg_s = int(beg * 16000)
26
+ end_s = int(end * 16000)
27
+ return audio[beg_s:end_s]
28
+
29
+
30
+ # Whisper backend
31
+
32
+ class ASRBase:
33
+ sep = " " # join transcribe words with this character (" " for whisper_timestamped,
34
+
35
+ # "" for faster-whisper because it emits the spaces when neeeded)
36
+
37
+ def __init__(self, lan, modelsize=None, cache_dir=None, model_dir=None, logfile=sys.stderr):
38
+ self.logfile = logfile
39
+
40
+ self.transcribe_kargs = {}
41
+ if lan == "auto":
42
+ self.original_language = None
43
+ else:
44
+ self.original_language = lan
45
+
46
+ self.model = self.load_model(modelsize, cache_dir, model_dir)
47
+
48
+ def load_model(self, modelsize, cache_dir):
49
+ raise NotImplemented("must be implemented in the child class")
50
+
51
+ def transcribe(self, audio, init_prompt=""):
52
+ raise NotImplemented("must be implemented in the child class")
53
+
54
+ def use_vad(self):
55
+ raise NotImplemented("must be implemented in the child class")
56
+
57
+
58
+ # class WhisperTimestampedASR(ASRBase):
59
+ # """Uses whisper_timestamped library as the backend. Initially, we tested the code on this backend. It worked, but slower than faster-whisper.
60
+ # On the other hand, the installation for GPU could be easier.
61
+ # """
62
+ #
63
+ # sep = " "
64
+ #
65
+ # def load_model(self, modelsize=None, cache_dir=None, model_dir=None):
66
+ # import whisper
67
+ # import whisper_timestamped
68
+ # from whisper_timestamped import transcribe_timestamped
69
+ # self.transcribe_timestamped = transcribe_timestamped
70
+ # if model_dir is not None:
71
+ # logger.debug("ignoring model_dir, not implemented")
72
+ # return whisper.load_model(modelsize, download_root=cache_dir)
73
+ #
74
+ # def transcribe(self, audio, init_prompt=""):
75
+ # result = self.transcribe_timestamped(self.model,
76
+ # audio, language=self.original_language,
77
+ # initial_prompt=init_prompt, verbose=None,
78
+ # condition_on_previous_text=True, **self.transcribe_kargs)
79
+ # return result
80
+ #
81
+ # def ts_words(self, r):
82
+ # # return: transcribe result object to [(beg,end,"word1"), ...]
83
+ # o = []
84
+ # for s in r["segments"]:
85
+ # for w in s["words"]:
86
+ # t = (w["start"], w["end"], w["text"])
87
+ # o.append(t)
88
+ # return o
89
+ #
90
+ # def segments_end_ts(self, res):
91
+ # return [s["end"] for s in res["segments"]]
92
+ #
93
+ # def use_vad(self):
94
+ # self.transcribe_kargs["vad"] = True
95
+ #
96
+ # def set_translate_task(self):
97
+ # self.transcribe_kargs["task"] = "translate"
98
+ #
99
+
100
+ class FasterWhisperASR(ASRBase):
101
+ logging.info(f"In faster whisper ASR")
102
+ """Uses faster-whisper library as the backend. Works much faster, appx 4-times (in offline mode). For GPU, it requires installation with a specific CUDNN version.
103
+ """
104
+
105
+ sep = ""
106
+
107
+ def load_model(self, modelsize=None, cache_dir=None, model_dir=None):
108
+ from faster_whisper import WhisperModel
109
+ # logging.getLogger("faster_whisper").setLevel(logger.level)
110
+
111
+ logging.info("Starting model loading process...")
112
+ logging.debug(f"Model loading parameters - modelsize: {modelsize}, cache_dir: {cache_dir}, model_dir: {model_dir}")
113
+
114
+ if model_dir is not None:
115
+ logger.debug(
116
+ f"Loading whisper model from model_dir {model_dir}. modelsize and cache_dir parameters are not used.")
117
+ model_size_or_path = model_dir
118
+ elif modelsize is not None:
119
+ model_size_or_path = modelsize
120
+ else:
121
+ raise ValueError("modelsize or model_dir parameter must be set")
122
+
123
+ try:
124
+ logging.info(f"Loading WhisperModel on device: ")
125
+ model = WhisperModel(model_size_or_path, device="cuda", compute_type="float16", download_root=cache_dir)
126
+ logging.info("Model loaded successfully.")
127
+ except Exception as e:
128
+ logging.error(f"An error occurred while loading the model: {e}", exc_info=True)
129
+ raise
130
+
131
+
132
+ # this worked fast and reliably on NVIDIA L40
133
+ #model = WhisperModel(model_size_or_path, device="cuda", compute_type="float16", download_root=cache_dir)
134
+
135
+ # or run on GPU with INT8
136
+ # tested: the transcripts were different, probably worse than with FP16, and it was slightly (appx 20%) slower
137
+ # model = WhisperModel(model_size, device="cuda", compute_type="int8_float16")
138
+
139
+ # or run on CPU with INT8
140
+ # tested: works, but slow, appx 10-times than cuda FP16
141
+ # model = WhisperModel(modelsize, device="cpu", compute_type="int8") #, download_root="faster-disk-cache-dir/")
142
+ return model
143
+
144
+ def transcribe(self, audio, init_prompt=""):
145
+ logging.info("Starting transcription process...")
146
+ logging.debug(f"Transcription parameters - language: {self.original_language}, initial_prompt: '{init_prompt}'")
147
+
148
+ try:
149
+ # tested: beam_size=5 is faster and better than 1 (on one 200 second document from En ESIC, min chunk 0.01)
150
+ segments, info = self.model.transcribe(audio, language=self.original_language, initial_prompt=init_prompt,
151
+ beam_size=5, word_timestamps=True, condition_on_previous_text=True,
152
+ **self.transcribe_kargs)
153
+ logging.info("Transcription completed successfully.")
154
+ logging.debug(f"Transcription info: {info}")
155
+ except Exception as e:
156
+ logging.error(f"An error occurred during transcription: {e}", exc_info=True)
157
+ raise
158
+ return list(segments)
159
+
160
+ def ts_words(self, segments):
161
+ o = []
162
+ for segment in segments:
163
+ for word in segment.words:
164
+ if segment.no_speech_prob > 0.9:
165
+ continue
166
+ # not stripping the spaces -- should not be merged with them!
167
+ w = word.word
168
+ t = (word.start, word.end, w)
169
+ o.append(t)
170
+ return o
171
+
172
+ def segments_end_ts(self, res):
173
+ return [s.end for s in res]
174
+
175
+ def use_vad(self):
176
+ self.transcribe_kargs["vad_filter"] = True
177
+
178
+ def set_translate_task(self):
179
+ self.transcribe_kargs["task"] = "translate"
180
+
181
+
182
+ # class OpenaiApiASR(ASRBase):
183
+ # """Uses OpenAI's Whisper API for audio transcription."""
184
+ #
185
+ # def __init__(self, lan=None, temperature=0, logfile=sys.stderr):
186
+ # self.logfile = logfile
187
+ #
188
+ # self.modelname = "whisper-1"
189
+ # self.original_language = None if lan == "auto" else lan # ISO-639-1 language code
190
+ # self.response_format = "verbose_json"
191
+ # self.temperature = temperature
192
+ #
193
+ # self.load_model()
194
+ #
195
+ # self.use_vad_opt = False
196
+ #
197
+ # # reset the task in set_translate_task
198
+ # self.task = "transcribe"
199
+ #
200
+ # def load_model(self, *args, **kwargs):
201
+ # from openai import OpenAI
202
+ # self.client = OpenAI()
203
+ #
204
+ # self.transcribed_seconds = 0 # for logging how many seconds were processed by API, to know the cost
205
+ #
206
+ # def ts_words(self, segments):
207
+ # no_speech_segments = []
208
+ # if self.use_vad_opt:
209
+ # for segment in segments.segments:
210
+ # # TODO: threshold can be set from outside
211
+ # if segment["no_speech_prob"] > 0.8:
212
+ # no_speech_segments.append((segment.get("start"), segment.get("end")))
213
+ #
214
+ # o = []
215
+ # for word in segments.words:
216
+ # start = word.get("start")
217
+ # end = word.get("end")
218
+ # if any(s[0] <= start <= s[1] for s in no_speech_segments):
219
+ # # print("Skipping word", word.get("word"), "because it's in a no-speech segment")
220
+ # continue
221
+ # o.append((start, end, word.get("word")))
222
+ # return o
223
+ #
224
+ # def segments_end_ts(self, res):
225
+ # return [s["end"] for s in res.words]
226
+ #
227
+ # def transcribe(self, audio_data, prompt=None, *args, **kwargs):
228
+ # # Write the audio data to a buffer
229
+ # buffer = io.BytesIO()
230
+ # buffer.name = "temp.wav"
231
+ # sf.write(buffer, audio_data, samplerate=16000, format='WAV', subtype='PCM_16')
232
+ # buffer.seek(0) # Reset buffer's position to the beginning
233
+ #
234
+ # self.transcribed_seconds += math.ceil(len(audio_data) / 16000) # it rounds up to the whole seconds
235
+ #
236
+ # params = {
237
+ # "model": self.modelname,
238
+ # "file": buffer,
239
+ # "response_format": self.response_format,
240
+ # "temperature": self.temperature,
241
+ # "timestamp_granularities": ["word", "segment"]
242
+ # }
243
+ # if self.task != "translate" and self.original_language:
244
+ # params["language"] = self.original_language
245
+ # if prompt:
246
+ # params["prompt"] = prompt
247
+ #
248
+ # if self.task == "translate":
249
+ # proc = self.client.audio.translations
250
+ # else:
251
+ # proc = self.client.audio.transcriptions
252
+ #
253
+ # # Process transcription/translation
254
+ # transcript = proc.create(**params)
255
+ # logger.debug(f"OpenAI API processed accumulated {self.transcribed_seconds} seconds")
256
+ #
257
+ # return transcript
258
+ #
259
+ # def use_vad(self):
260
+ # self.use_vad_opt = True
261
+ #
262
+ # def set_translate_task(self):
263
+ # self.task = "translate"
264
+ #
265
+
266
+ class HypothesisBuffer:
267
+
268
+ def __init__(self, logfile=sys.stderr):
269
+ self.commited_in_buffer = []
270
+ self.buffer = []
271
+ self.new = []
272
+
273
+ self.last_commited_time = 0
274
+ self.last_commited_word = None
275
+
276
+ self.logfile = logfile
277
+
278
+ def insert(self, new, offset):
279
+ # compare self.commited_in_buffer and new. It inserts only the words in new that extend the commited_in_buffer, it means they are roughly behind last_commited_time and new in content
280
+ # the new tail is added to self.new
281
+
282
+ new = [(a + offset, b + offset, t) for a, b, t in new]
283
+ self.new = [(a, b, t) for a, b, t in new if a > self.last_commited_time - 0.1]
284
+
285
+ if len(self.new) >= 1:
286
+ a, b, t = self.new[0]
287
+ if abs(a - self.last_commited_time) < 1:
288
+ if self.commited_in_buffer:
289
+ # it's going to search for 1, 2, ..., 5 consecutive words (n-grams) that are identical in commited and new. If they are, they're dropped.
290
+ cn = len(self.commited_in_buffer)
291
+ nn = len(self.new)
292
+ for i in range(1, min(min(cn, nn), 5) + 1): # 5 is the maximum
293
+ c = " ".join([self.commited_in_buffer[-j][2] for j in range(1, i + 1)][::-1])
294
+ tail = " ".join(self.new[j - 1][2] for j in range(1, i + 1))
295
+ if c == tail:
296
+ words = []
297
+ for j in range(i):
298
+ words.append(repr(self.new.pop(0)))
299
+ words_msg = " ".join(words)
300
+ logger.debug(f"removing last {i} words: {words_msg}")
301
+ break
302
+
303
+ def flush(self):
304
+ # returns commited chunk = the longest common prefix of 2 last inserts.
305
+
306
+ commit = []
307
+ while self.new:
308
+ na, nb, nt = self.new[0]
309
+
310
+ if len(self.buffer) == 0:
311
+ break
312
+
313
+ if nt == self.buffer[0][2]:
314
+ commit.append((na, nb, nt))
315
+ self.last_commited_word = nt
316
+ self.last_commited_time = nb
317
+ self.buffer.pop(0)
318
+ self.new.pop(0)
319
+ else:
320
+ break
321
+ self.buffer = self.new
322
+ self.new = []
323
+ self.commited_in_buffer.extend(commit)
324
+ return commit
325
+
326
+ def pop_commited(self, time):
327
+ while self.commited_in_buffer and self.commited_in_buffer[0][1] <= time:
328
+ self.commited_in_buffer.pop(0)
329
+
330
+ def complete(self):
331
+ return self.buffer
332
+
333
+
334
+ class OnlineASRProcessor:
335
+ SAMPLING_RATE = 16000
336
+
337
+ def __init__(self, asr, tokenizer=None, buffer_trimming=("segment", 15), logfile=sys.stderr):
338
+ """asr: WhisperASR object
339
+ tokenizer: sentence tokenizer object for the target language. Must have a method *split* that behaves like the one of MosesTokenizer. It can be None, if "segment" buffer trimming option is used, then tokenizer is not used at all.
340
+ ("segment", 15)
341
+ buffer_trimming: a pair of (option, seconds), where option is either "sentence" or "segment", and seconds is a number. Buffer is trimmed if it is longer than "seconds" threshold. Default is the most recommended option.
342
+ logfile: where to store the log.
343
+ """
344
+ self.asr = asr
345
+ self.tokenizer = tokenizer
346
+ self.logfile = logfile
347
+
348
+ self.init()
349
+
350
+ self.buffer_trimming_way, self.buffer_trimming_sec = buffer_trimming
351
+
352
+ def init(self, offset=None):
353
+ """run this when starting or restarting processing"""
354
+ self.audio_buffer = np.array([], dtype=np.float32)
355
+ self.transcript_buffer = HypothesisBuffer(logfile=self.logfile)
356
+ self.buffer_time_offset = 0
357
+ if offset is not None:
358
+ self.buffer_time_offset = offset
359
+ self.transcript_buffer.last_commited_time = self.buffer_time_offset
360
+ self.commited = []
361
+
362
+ def insert_audio_chunk(self, audio):
363
+ self.audio_buffer = np.append(self.audio_buffer, audio)
364
+
365
+ def prompt(self):
366
+ """Returns a tuple: (prompt, context), where "prompt" is a 200-character suffix of commited text that is inside of the scrolled away part of audio buffer.
367
+ "context" is the commited text that is inside the audio buffer. It is transcribed again and skipped. It is returned only for debugging and logging reasons.
368
+ """
369
+ k = max(0, len(self.commited) - 1)
370
+ while k > 0 and self.commited[k - 1][1] > self.buffer_time_offset:
371
+ k -= 1
372
+
373
+ p = self.commited[:k]
374
+ p = [t for _, _, t in p]
375
+ prompt = []
376
+ l = 0
377
+ while p and l < 200: # 200 characters prompt size
378
+ x = p.pop(-1)
379
+ l += len(x) + 1
380
+ prompt.append(x)
381
+ non_prompt = self.commited[k:]
382
+ return self.asr.sep.join(prompt[::-1]), self.asr.sep.join(t for _, _, t in non_prompt)
383
+
384
+ def process_iter(self):
385
+ """Runs on the current audio buffer.
386
+ Returns: a tuple (beg_timestamp, end_timestamp, "text"), or (None, None, "").
387
+ The non-emty text is confirmed (committed) partial transcript.
388
+ """
389
+
390
+ prompt, non_prompt = self.prompt()
391
+ logger.debug(f"PROMPT: {prompt}")
392
+ logger.debug(f"CONTEXT: {non_prompt}")
393
+ logger.debug(
394
+ f"transcribing {len(self.audio_buffer) / self.SAMPLING_RATE:2.2f} seconds from {self.buffer_time_offset:2.2f}")
395
+ res = self.asr.transcribe(self.audio_buffer, init_prompt=prompt)
396
+
397
+ # transform to [(beg,end,"word1"), ...]
398
+ tsw = self.asr.ts_words(res)
399
+
400
+ self.transcript_buffer.insert(tsw, self.buffer_time_offset)
401
+ o = self.transcript_buffer.flush()
402
+ self.commited.extend(o)
403
+ completed = self.to_flush(o)
404
+ logger.debug(f">>>>COMPLETE NOW: {completed}")
405
+ the_rest = self.to_flush(self.transcript_buffer.complete())
406
+ logger.debug(f"INCOMPLETE: {the_rest}")
407
+
408
+ # there is a newly confirmed text
409
+
410
+ if o and self.buffer_trimming_way == "sentence": # trim the completed sentences
411
+ if len(self.audio_buffer) / self.SAMPLING_RATE > self.buffer_trimming_sec: # longer than this
412
+ self.chunk_completed_sentence()
413
+
414
+ if self.buffer_trimming_way == "segment":
415
+ s = self.buffer_trimming_sec # trim the completed segments longer than s,
416
+ else:
417
+ s = 30 # if the audio buffer is longer than 30s, trim it
418
+
419
+ if len(self.audio_buffer) / self.SAMPLING_RATE > s:
420
+ self.chunk_completed_segment(res)
421
+
422
+ # alternative: on any word
423
+ # l = self.buffer_time_offset + len(self.audio_buffer)/self.SAMPLING_RATE - 10
424
+ # let's find commited word that is less
425
+ # k = len(self.commited)-1
426
+ # while k>0 and self.commited[k][1] > l:
427
+ # k -= 1
428
+ # t = self.commited[k][1]
429
+ logger.debug("chunking segment")
430
+ # self.chunk_at(t)
431
+
432
+ logger.debug(f"len of buffer now: {len(self.audio_buffer) / self.SAMPLING_RATE:2.2f}")
433
+ return self.to_flush(o)
434
+
435
+ def chunk_completed_sentence(self):
436
+ if self.commited == []: return
437
+ logger.debug(self.commited)
438
+ sents = self.words_to_sentences(self.commited)
439
+ for s in sents:
440
+ logger.debug(f"\t\tSENT: {s}")
441
+ if len(sents) < 2:
442
+ return
443
+ while len(sents) > 2:
444
+ sents.pop(0)
445
+ # we will continue with audio processing at this timestamp
446
+ chunk_at = sents[-2][1]
447
+
448
+ logger.debug(f"--- sentence chunked at {chunk_at:2.2f}")
449
+ self.chunk_at(chunk_at)
450
+
451
+ def chunk_completed_segment(self, res):
452
+ if self.commited == []: return
453
+
454
+ ends = self.asr.segments_end_ts(res)
455
+
456
+ t = self.commited[-1][1]
457
+
458
+ if len(ends) > 1:
459
+
460
+ e = ends[-2] + self.buffer_time_offset
461
+ while len(ends) > 2 and e > t:
462
+ ends.pop(-1)
463
+ e = ends[-2] + self.buffer_time_offset
464
+ if e <= t:
465
+ logger.debug(f"--- segment chunked at {e:2.2f}")
466
+ self.chunk_at(e)
467
+ else:
468
+ logger.debug(f"--- last segment not within commited area")
469
+ else:
470
+ logger.debug(f"--- not enough segments to chunk")
471
+
472
+ def chunk_at(self, time):
473
+ """trims the hypothesis and audio buffer at "time"
474
+ """
475
+ self.transcript_buffer.pop_commited(time)
476
+ cut_seconds = time - self.buffer_time_offset
477
+ self.audio_buffer = self.audio_buffer[int(cut_seconds * self.SAMPLING_RATE):]
478
+ self.buffer_time_offset = time
479
+
480
+ def words_to_sentences(self, words):
481
+ """Uses self.tokenizer for sentence segmentation of words.
482
+ Returns: [(beg,end,"sentence 1"),...]
483
+ """
484
+
485
+ cwords = [w for w in words]
486
+ t = " ".join(o[2] for o in cwords)
487
+ s = self.tokenizer.split(t)
488
+ out = []
489
+ while s:
490
+ beg = None
491
+ end = None
492
+ sent = s.pop(0).strip()
493
+ fsent = sent
494
+ while cwords:
495
+ b, e, w = cwords.pop(0)
496
+ w = w.strip()
497
+ if beg is None and sent.startswith(w):
498
+ beg = b
499
+ elif end is None and sent == w:
500
+ end = e
501
+ out.append((beg, end, fsent))
502
+ break
503
+ sent = sent[len(w):].strip()
504
+ return out
505
+
506
+ def finish(self):
507
+ """Flush the incomplete text when the whole processing ends.
508
+ Returns: the same format as self.process_iter()
509
+ """
510
+ o = self.transcript_buffer.complete()
511
+ f = self.to_flush(o)
512
+ logger.debug(f"last, noncommited: {f}")
513
+ self.buffer_time_offset += len(self.audio_buffer) / 16000
514
+ return f
515
+
516
+ def to_flush(self, sents, sep=None, offset=0, ):
517
+ # concatenates the timestamped words or sentences into one sequence that is flushed in one line
518
+ # sents: [(beg1, end1, "sentence1"), ...] or [] if empty
519
+ # return: (beg1,end-of-last-sentence,"concatenation of sentences") or (None, None, "") if empty
520
+ if sep is None:
521
+ sep = self.asr.sep
522
+ t = sep.join(s[2] for s in sents)
523
+ if len(sents) == 0:
524
+ b = None
525
+ e = None
526
+ else:
527
+ b = offset + sents[0][0]
528
+ e = offset + sents[-1][1]
529
+ return (b, e, t)
530
+
531
+
532
+ class VACOnlineASRProcessor(OnlineASRProcessor):
533
+ '''Wraps OnlineASRProcessor with VAC (Voice Activity Controller).
534
+
535
+ It works the same way as OnlineASRProcessor: it receives chunks of audio (e.g. 0.04 seconds),
536
+ it runs VAD and continuously detects whether there is speech or not.
537
+ When it detects end of speech (non-voice for 500ms), it makes OnlineASRProcessor to end the utterance immediately.
538
+ '''
539
+
540
+ def __init__(self, online_chunk_size, *a, **kw):
541
+ self.online_chunk_size = online_chunk_size
542
+
543
+ self.online = OnlineASRProcessor(*a, **kw)
544
+
545
+ # VAC:
546
+ import torch
547
+ model, _ = torch.hub.load(
548
+ repo_or_dir='snakers4/silero-vad',
549
+ model='silero_vad'
550
+ )
551
+ #from silero_vad import VADIterator
552
+ #self.vac = VADIterator(model) # we use all the default options: 500ms silence, etc.
553
+
554
+ self.logfile = self.online.logfile
555
+ self.init()
556
+
557
+ def init(self):
558
+ self.online.init()
559
+ self.vac.reset_states()
560
+ self.current_online_chunk_buffer_size = 0
561
+
562
+ self.is_currently_final = False
563
+
564
+ self.status = None # or "voice" or "nonvoice"
565
+ self.audio_buffer = np.array([], dtype=np.float32)
566
+ self.buffer_offset = 0 # in frames
567
+
568
+ def clear_buffer(self):
569
+ self.buffer_offset += len(self.audio_buffer)
570
+ self.audio_buffer = np.array([], dtype=np.float32)
571
+
572
+ def insert_audio_chunk(self, audio):
573
+ res = self.vac(audio)
574
+ self.audio_buffer = np.append(self.audio_buffer, audio)
575
+
576
+ if res is not None:
577
+ frame = list(res.values())[0]
578
+ if 'start' in res and 'end' not in res:
579
+ self.status = 'voice'
580
+ send_audio = self.audio_buffer[frame - self.buffer_offset:]
581
+ self.online.init(offset=frame / self.SAMPLING_RATE)
582
+ self.online.insert_audio_chunk(send_audio)
583
+ self.current_online_chunk_buffer_size += len(send_audio)
584
+ self.clear_buffer()
585
+ elif 'end' in res and 'start' not in res:
586
+ self.status = 'nonvoice'
587
+ send_audio = self.audio_buffer[:frame - self.buffer_offset]
588
+ self.online.insert_audio_chunk(send_audio)
589
+ self.current_online_chunk_buffer_size += len(send_audio)
590
+ self.is_currently_final = True
591
+ self.clear_buffer()
592
+ else:
593
+ # It doesn't happen in the current code.
594
+ raise NotImplemented("both start and end of voice in one chunk!!!")
595
+ else:
596
+ if self.status == 'voice':
597
+ self.online.insert_audio_chunk(self.audio_buffer)
598
+ self.current_online_chunk_buffer_size += len(self.audio_buffer)
599
+ self.clear_buffer()
600
+ else:
601
+ # We keep 1 second because VAD may later find start of voice in it.
602
+ # But we trim it to prevent OOM.
603
+ self.buffer_offset += max(0, len(self.audio_buffer) - self.SAMPLING_RATE)
604
+ self.audio_buffer = self.audio_buffer[-self.SAMPLING_RATE:]
605
+
606
+ def process_iter(self):
607
+ if self.is_currently_final:
608
+ return self.finish()
609
+ elif self.current_online_chunk_buffer_size > self.SAMPLING_RATE * self.online_chunk_size:
610
+ self.current_online_chunk_buffer_size = 0
611
+ ret = self.online.process_iter()
612
+ return ret
613
+ else:
614
+ print("no online update, only VAD", self.status, file=self.logfile)
615
+ return (None, None, "")
616
+
617
+ def finish(self):
618
+ ret = self.online.finish()
619
+ self.current_online_chunk_buffer_size = 0
620
+ self.is_currently_final = False
621
+ return ret
622
+
623
+
624
+ WHISPER_LANG_CODES = "af,am,ar,as,az,ba,be,bg,bn,bo,br,bs,ca,cs,cy,da,de,el,en,es,et,eu,fa,fi,fo,fr,gl,gu,ha,haw,he,hi,hr,ht,hu,hy,id,is,it,ja,jw,ka,kk,km,kn,ko,la,lb,ln,lo,lt,lv,mg,mi,mk,ml,mn,mr,ms,mt,my,ne,nl,nn,no,oc,pa,pl,ps,pt,ro,ru,sa,sd,si,sk,sl,sn,so,sq,sr,su,sv,sw,ta,te,tg,th,tk,tl,tr,tt,uk,ur,uz,vi,yi,yo,zh".split(
625
+ ",")
626
+
627
+
628
+ def create_tokenizer(lan):
629
+ """returns an object that has split function that works like the one of MosesTokenizer"""
630
+
631
+ assert lan in WHISPER_LANG_CODES, "language must be Whisper's supported lang code: " + " ".join(WHISPER_LANG_CODES)
632
+
633
+ if lan == "uk":
634
+ import tokenize_uk
635
+ class UkrainianTokenizer:
636
+ def split(self, text):
637
+ return tokenize_uk.tokenize_sents(text)
638
+
639
+ return UkrainianTokenizer()
640
+
641
+ # supported by fast-mosestokenizer
642
+ # if lan in "as bn ca cs de el en es et fi fr ga gu hi hu is it kn lt lv ml mni mr nl or pa pl pt ro ru sk sl sv ta te yue zh".split():
643
+ # #from mosestokenizer import MosesTokenizer
644
+ # #return MosesTokenizer(lan)
645
+
646
+ # the following languages are in Whisper, but not in wtpsplit:
647
+ if lan in "as ba bo br bs fo haw hr ht jw lb ln lo mi nn oc sa sd sn so su sw tk tl tt".split():
648
+ logger.debug(f"{lan} code is not supported by wtpsplit. Going to use None lang_code option.")
649
+ lan = None
650
+
651
+ #from wtpsplit import WtP
652
+ # downloads the model from huggingface on the first use
653
+ #wtp = WtP("wtp-canine-s-12l-no-adapters")
654
+
655
+ # class WtPtok:
656
+ # def split(self, sent):
657
+ # #return wtp.split(sent, lang_code=lan)
658
+ #
659
+ # return WtPtok()
660
+
661
+
662
+ def add_shared_args(parser):
663
+ """shared args for simulation (this entry point) and server
664
+ parser: argparse.ArgumentParser object
665
+ """
666
+ parser.add_argument('--min-chunk-size', type=float, default=1.0,
667
+ help='Minimum audio chunk size in seconds. It waits up to this time to do processing. If the processing takes shorter time, it waits, otherwise it processes the whole segment that was received by this time.')
668
+ parser.add_argument('--model', type=str, default='large-v2',
669
+ choices="tiny.en,tiny,base.en,base,small.en,small,medium.en,medium,large-v1,large-v2,large-v3,large".split(
670
+ ","),
671
+ help="Name size of the Whisper model to use (default: large-v2). The model is automatically downloaded from the model hub if not present in model cache dir.")
672
+ parser.add_argument('--model_cache_dir', type=str, default=None,
673
+ help="Overriding the default model cache dir where models downloaded from the hub are saved")
674
+ parser.add_argument('--model_dir', type=str, default=None,
675
+ help="Dir where Whisper model.bin and other files are saved. This option overrides --model and --model_cache_dir parameter.")
676
+ parser.add_argument('--lan', '--language', type=str, default='auto',
677
+ help="Source language code, e.g. en,de,cs, or 'auto' for language detection.")
678
+ parser.add_argument('--task', type=str, default='transcribe', choices=["transcribe", "translate"],
679
+ help="Transcribe or translate.")
680
+ parser.add_argument('--backend', type=str, default="faster-whisper",
681
+ choices=["faster-whisper", "whisper_timestamped", "openai-api"],
682
+ help='Load only this backend for Whisper processing.')
683
+ parser.add_argument('--vac', action="store_true", default=False,
684
+ help='Use VAC = voice activity controller. Recommended. Requires torch.')
685
+ parser.add_argument('--vac-chunk-size', type=float, default=0.04, help='VAC sample size in seconds.')
686
+ parser.add_argument('--vad', action="store_true", default=False,
687
+ help='Use VAD = voice activity detection, with the default parameters.')
688
+ parser.add_argument('--buffer_trimming', type=str, default="segment", choices=["sentence", "segment"],
689
+ help='Buffer trimming strategy -- trim completed sentences marked with punctuation mark and detected by sentence segmenter, or the completed segments returned by Whisper. Sentence segmenter must be installed for "sentence" option.')
690
+ parser.add_argument('--buffer_trimming_sec', type=float, default=15,
691
+ help='Buffer trimming length threshold in seconds. If buffer length is longer, trimming sentence/segment is triggered.')
692
+ parser.add_argument("-l", "--log-level", dest="log_level",
693
+ choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the log level",
694
+ default='DEBUG')
695
+
696
+
697
+ def asr_factory(args, logfile=sys.stderr):
698
+ """
699
+ Creates and configures an ASR and ASR Online instance based on the specified backend and arguments.
700
+ """
701
+ backend = args.backend
702
+ if backend == "openai-api":
703
+ logger.debug("Using OpenAI API.")
704
+ #asr = OpenaiApiASR(lan=args.lan)
705
+ else:
706
+ if backend == "faster-whisper":
707
+ logger.debug("Using FasterWhisper.")
708
+ print("using faster-whisper from whisper-online")
709
+ asr_cls = FasterWhisperASR
710
+ #else:
711
+ #asr_cls = WhisperTimestampedASR
712
+
713
+ # Only for FasterWhisperASR and WhisperTimestampedASR
714
+ size = args.model
715
+ t = time.time()
716
+ logger.info(f"Loading Whisper {size} model for {args.lan}...")
717
+ asr = asr_cls(modelsize=size, lan=args.lan, cache_dir=args.model_cache_dir, model_dir=args.model_dir)
718
+ e = time.time()
719
+ logger.info(f"done. It took {round(e - t, 2)} seconds.")
720
+
721
+ # Apply common configurations
722
+ if getattr(args, 'vad', False): # Checks if VAD argument is present and True
723
+ logger.info("Setting VAD filter")
724
+ asr.use_vad()
725
+
726
+ language = args.lan
727
+ if args.task == "translate":
728
+ asr.set_translate_task()
729
+ tgt_language = "en" # Whisper translates into English
730
+ else:
731
+ tgt_language = language # Whisper transcribes in this language
732
+
733
+ # Create the tokenizer
734
+ if args.buffer_trimming == "sentence":
735
+ tokenizer = create_tokenizer(tgt_language)
736
+ else:
737
+ tokenizer = None
738
+
739
+ # Create the OnlineASRProcessor
740
+ if args.vac:
741
+
742
+ online = VACOnlineASRProcessor(args.min_chunk_size, asr, tokenizer, logfile=logfile,
743
+ buffer_trimming=(args.buffer_trimming, args.buffer_trimming_sec))
744
+ else:
745
+ online = OnlineASRProcessor(asr, tokenizer, logfile=logfile,
746
+ buffer_trimming=(args.buffer_trimming, args.buffer_trimming_sec))
747
+
748
+ return asr, online
749
+
750
+
751
+ def set_logging(args, logger, other="_server"):
752
+ logging.basicConfig( # format='%(name)s
753
+ format='%(levelname)s\t%(message)s')
754
+ logger.setLevel(args.log_level)
755
+ logging.getLogger("whisper_online" + other).setLevel(args.log_level)
756
+
757
+
758
+ # logging.getLogger("whisper_online_server").setLevel(args.log_level)
759
+
760
+
761
+ if __name__ == "__main__":
762
+
763
+ import argparse
764
+
765
+ parser = argparse.ArgumentParser()
766
+ parser.add_argument('audio_path', type=str,
767
+ help="Filename of 16kHz mono channel wav, on which live streaming is simulated.")
768
+ add_shared_args(parser)
769
+ parser.add_argument('--start_at', type=float, default=0.0, help='Start processing audio at this time.')
770
+ parser.add_argument('--offline', action="store_true", default=False, help='Offline mode.')
771
+ parser.add_argument('--comp_unaware', action="store_true", default=False,
772
+ help='Computationally unaware simulation.')
773
+
774
+ args = parser.parse_args()
775
+
776
+ # reset to store stderr to different file stream, e.g. open(os.devnull,"w")
777
+ logfile = sys.stderr
778
+
779
+ if args.offline and args.comp_unaware:
780
+ logger.error("No or one option from --offline and --comp_unaware are available, not both. Exiting.")
781
+ sys.exit(1)
782
+
783
+ # if args.log_level:
784
+ # logging.basicConfig(format='whisper-%(levelname)s:%(name)s: %(message)s',
785
+ # level=getattr(logging, args.log_level))
786
+
787
+ set_logging(args, logger)
788
+
789
+ audio_path = args.audio_path
790
+
791
+ SAMPLING_RATE = 16000
792
+ duration = len(load_audio(audio_path)) / SAMPLING_RATE
793
+ logger.info("Audio duration is: %2.2f seconds" % duration)
794
+
795
+ asr, online = asr_factory(args, logfile=logfile)
796
+ if args.vac:
797
+ min_chunk = args.vac_chunk_size
798
+ else:
799
+ min_chunk = args.min_chunk_size
800
+
801
+ # load the audio into the LRU cache before we start the timer
802
+ a = load_audio_chunk(audio_path, 0, 1)
803
+
804
+ # warm up the ASR because the very first transcribe takes much more time than the other
805
+ asr.transcribe(a)
806
+
807
+ beg = args.start_at
808
+ start = time.time() - beg
809
+
810
+
811
+ def output_transcript(o, now=None):
812
+ # output format in stdout is like:
813
+ # 4186.3606 0 1720 Takhle to je
814
+ # - the first three words are:
815
+ # - emission time from beginning of processing, in milliseconds
816
+ # - beg and end timestamp of the text segment, as estimated by Whisper model. The timestamps are not accurate, but they're useful anyway
817
+ # - the next words: segment transcript
818
+ if now is None:
819
+ now = time.time() - start
820
+ if o[0] is not None:
821
+ print("%1.4f %1.0f %1.0f %s" % (now * 1000, o[0] * 1000, o[1] * 1000, o[2]), file=logfile, flush=True)
822
+ print("%1.4f %1.0f %1.0f %s" % (now * 1000, o[0] * 1000, o[1] * 1000, o[2]), flush=True)
823
+ else:
824
+ # No text, so no output
825
+ pass
826
+
827
+
828
+ if args.offline: ## offline mode processing (for testing/debugging)
829
+ a = load_audio(audio_path)
830
+ online.insert_audio_chunk(a)
831
+ try:
832
+ o = online.process_iter()
833
+ except AssertionError as e:
834
+ logger.error(f"assertion error: {repr(e)}")
835
+ else:
836
+ output_transcript(o)
837
+ now = None
838
+ elif args.comp_unaware: # computational unaware mode
839
+ end = beg + min_chunk
840
+ while True:
841
+ a = load_audio_chunk(audio_path, beg, end)
842
+ online.insert_audio_chunk(a)
843
+ try:
844
+ o = online.process_iter()
845
+ except AssertionError as e:
846
+ logger.error(f"assertion error: {repr(e)}")
847
+ pass
848
+ else:
849
+ output_transcript(o, now=end)
850
+
851
+ logger.debug(f"## last processed {end:.2f}s")
852
+
853
+ if end >= duration:
854
+ break
855
+
856
+ beg = end
857
+
858
+ if end + min_chunk > duration:
859
+ end = duration
860
+ else:
861
+ end += min_chunk
862
+ now = duration
863
+
864
+ else: # online = simultaneous mode
865
+ end = 0
866
+ while True:
867
+ now = time.time() - start
868
+ if now < end + min_chunk:
869
+ time.sleep(min_chunk + end - now)
870
+ end = time.time() - start
871
+ a = load_audio_chunk(audio_path, beg, end)
872
+ beg = end
873
+ online.insert_audio_chunk(a)
874
+
875
+ try:
876
+ o = online.process_iter()
877
+ except AssertionError as e:
878
+ logger.error(f"assertion error: {e}")
879
+ pass
880
+ else:
881
+ output_transcript(o)
882
+ now = time.time() - start
883
+ logger.debug(f"## last processed {end:.2f} s, now is {now:.2f}, the latency is {now - end:.2f}")
884
+
885
+ if end >= duration:
886
+ break
887
+ now = None
888
+
889
+ o = online.finish()
890
+ output_transcript(o, now=now)