goldpulpy commited on
Commit
13f6d73
·
1 Parent(s): b3e36db

Upload space

Browse files
.gitignore ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+ config.json
29
+ data/
30
+
31
+ # PyInstaller
32
+ # Usually these files are written by a python script from a template
33
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
34
+ *.manifest
35
+ *.spec
36
+
37
+ logs.txt
38
+ testmodule.py
39
+
40
+ # Installer logs
41
+ pip-log.txt
42
+ pip-delete-this-directory.txt
43
+
44
+ # Unit test / coverage reports
45
+ htmlcov/
46
+ .tox/
47
+ .nox/
48
+ .vscode/
49
+ .coverage
50
+ .coverage.*
51
+ .cache
52
+ nosetests.xml
53
+ coverage.xml
54
+ *.cover
55
+ *.py,cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+ cover/
59
+
60
+ # Translations
61
+ *.mo
62
+ *.pot
63
+
64
+ # Django stuff:
65
+ *.log
66
+
67
+ local_settings.py
68
+ db.sqlite3
69
+ db.sqlite3-journal
70
+
71
+ # Flask stuff:
72
+ instance/
73
+ .webassets-cache
74
+
75
+ # Scrapy stuff:
76
+ .scrapy
77
+
78
+ # Sphinx documentation
79
+ docs/_build/
80
+
81
+ # PyBuilder
82
+ .pybuilder/
83
+ target/
84
+
85
+ # Jupyter Notebook
86
+ .ipynb_checkpoints
87
+
88
+ # IPython
89
+ profile_default/
90
+ ipython_config.py
91
+
92
+ # pyenv
93
+ # For a library or package, you might want to ignore these files since the code is
94
+ # intended to run in multiple environments; otherwise, check them in:
95
+ # .python-version
96
+
97
+ # pipenv
98
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
99
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
100
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
101
+ # install all needed dependencies.
102
+ #Pipfile.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ #poetry.lock
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ #pdm.lock
114
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
115
+ # in version control.
116
+ # https://pdm.fming.dev/#use-with-ide
117
+ .pdm.toml
118
+
119
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
120
+ __pypackages__/
121
+
122
+ # Celery stuff
123
+ celerybeat-schedule
124
+ celerybeat.pid
125
+
126
+ # SageMath parsed files
127
+ *.sage.py
128
+
129
+ # Environments
130
+ .env
131
+ .venv
132
+ env/
133
+ venv/
134
+ ENV/
135
+ env.bak/
136
+ venv.bak/
137
+
138
+ # Spyder project settings
139
+ .spyderproject
140
+ .spyproject
141
+
142
+ # Rope project settings
143
+ .ropeproject
144
+
145
+ # mkdocs documentation
146
+ /site
147
+
148
+ # mypy
149
+ .mypy_cache/
150
+ .dmypy.json
151
+ dmypy.json
152
+
153
+ # Pyre type checker
154
+ .pyre/
155
+
156
+ # pytype static type analyzer
157
+ .pytype/
158
+
159
+ # Cython debug symbols
160
+ cython_debug/
161
+
162
+ # PyCharm
163
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
164
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
165
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
166
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
167
+ #.idea/
168
+
169
+
170
+ .model/
171
+ .back/
172
+ .model-small/
173
+ .model-vosk-large/
174
+ .conda/
175
+ .vscode/
176
+ .__pycache__/
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:12.5.1-cudnn-devel-ubuntu22.04
2
+
3
+ ENV PATH=${CUDA_HOME}/bin:${PATH}
4
+ ENV C_INCLUDE_PATH=${CUDA_HOME}/include:${C_INCLUDE_PATH}
5
+ ENV LIBRARY_PATH=${CUDA_HOME}/lib64:${LIBRARY_PATH}
6
+
7
+ RUN apt-get update && apt-get install -y \
8
+ python3-launchpadlib \
9
+ software-properties-common \
10
+ && apt-get update && apt-get install -y \
11
+ python3-pip python3\
12
+ python3-dev tensorrt \
13
+ && apt-get clean \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ RUN useradd -m -u 1000 user
17
+ USER user
18
+
19
+ WORKDIR /app
20
+
21
+ COPY --chown=user ./requirements.txt requirements.txt
22
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
23
+
24
+ COPY --chown=user . /app
25
+ EXPOSE 7860
26
+ CMD ["python3", "entrypoint.py"]
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
  title: STT
3
- emoji: 🏃
4
  colorFrom: indigo
5
- colorTo: pink
6
  sdk: docker
7
  pinned: false
8
  ---
 
1
  ---
2
  title: STT
3
+ emoji: 📝
4
  colorFrom: indigo
5
+ colorTo: red
6
  sdk: docker
7
  pinned: false
8
  ---
app.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from modules.routers import setup_routers
4
+ import torch
5
+
6
+ app = FastAPI()
7
+ app.add_middleware(
8
+ CORSMiddleware,
9
+ allow_origins=["*"],
10
+ allow_credentials=True,
11
+ allow_methods=["*"],
12
+ allow_headers=["*"]
13
+ )
14
+
15
+ print(f"Is CUDA available: {torch.cuda.is_available()}")
16
+
17
+ setup_routers(app)
entrypoint.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ import uvicorn
2
+ uvicorn.run("app:app", host="0.0.0.0", port=7860, ws="auto", log_level="info")
modules/models/__init__.py ADDED
File without changes
modules/models/silero_vad.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ # This is copied from silero-vad's vad_utils.py:
4
+ # https://github.com/snakers4/silero-vad/blob/f6b1294cb27590fb2452899df98fb234dfef1134/utils_vad.py#L340
5
+
6
+ # Their licence is MIT, same as ours: https://github.com/snakers4/silero-vad/blob/f6b1294cb27590fb2452899df98fb234dfef1134/LICENSE
7
+
8
+ class VADIterator:
9
+ def __init__(self,
10
+ model,
11
+ threshold: float = 0.5,
12
+ sampling_rate: int = 16000,
13
+ min_silence_duration_ms: int = 100,
14
+ speech_pad_ms: int = 30
15
+ ):
16
+
17
+ """
18
+ Class for stream imitation
19
+
20
+ Parameters
21
+ ----------
22
+ model: preloaded .jit silero VAD model
23
+
24
+ threshold: float (default - 0.5)
25
+ Speech threshold. Silero VAD outputs speech probabilities for each audio chunk, probabilities ABOVE this value are considered as SPEECH.
26
+ It is better to tune this parameter for each dataset separately, but "lazy" 0.5 is pretty good for most datasets.
27
+
28
+ sampling_rate: int (default - 16000)
29
+ Currently silero VAD models support 8000 and 16000 sample rates
30
+
31
+ min_silence_duration_ms: int (default - 100 milliseconds)
32
+ In the end of each speech chunk wait for min_silence_duration_ms before separating it
33
+
34
+ speech_pad_ms: int (default - 30 milliseconds)
35
+ Final speech chunks are padded by speech_pad_ms each side
36
+ """
37
+
38
+ self.model = model
39
+ self.threshold = threshold
40
+ self.sampling_rate = sampling_rate
41
+
42
+ if sampling_rate not in [8000, 16000]:
43
+ raise ValueError('VADIterator does not support sampling rates other than [8000, 16000]')
44
+
45
+ self.min_silence_samples = sampling_rate * min_silence_duration_ms / 1000
46
+ self.speech_pad_samples = sampling_rate * speech_pad_ms / 1000
47
+ self.reset_states()
48
+
49
+ def reset_states(self):
50
+
51
+ self.model.reset_states()
52
+ self.triggered = False
53
+ self.temp_end = 0
54
+ self.current_sample = 0
55
+
56
+ def __call__(self, x, return_seconds=False):
57
+ """
58
+ x: torch.Tensor
59
+ audio chunk (see examples in repo)
60
+
61
+ return_seconds: bool (default - False)
62
+ whether return timestamps in seconds (default - samples)
63
+ """
64
+
65
+ if not torch.is_tensor(x):
66
+ try:
67
+ x = torch.Tensor(x)
68
+ except:
69
+ raise TypeError("Audio cannot be casted to tensor. Cast it manually")
70
+
71
+ window_size_samples = len(x[0]) if x.dim() == 2 else len(x)
72
+ self.current_sample += window_size_samples
73
+
74
+ speech_prob = self.model(x, self.sampling_rate).item()
75
+
76
+ if (speech_prob >= self.threshold) and self.temp_end:
77
+ self.temp_end = 0
78
+
79
+ if (speech_prob >= self.threshold) and not self.triggered:
80
+ self.triggered = True
81
+ speech_start = self.current_sample - self.speech_pad_samples
82
+ return {'start': int(speech_start) if not return_seconds else round(speech_start / self.sampling_rate, 1)}
83
+
84
+ if (speech_prob < self.threshold - 0.15) and self.triggered:
85
+ if not self.temp_end:
86
+ self.temp_end = self.current_sample
87
+ if self.current_sample - self.temp_end < self.min_silence_samples:
88
+ return None
89
+ else:
90
+ speech_end = self.temp_end + self.speech_pad_samples
91
+ self.temp_end = 0
92
+ self.triggered = False
93
+ return {'end': int(speech_end) if not return_seconds else round(speech_end / self.sampling_rate, 1)}
94
+
95
+ return None
96
+
97
+
modules/models/speech_recognizer.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from modules.models.whisper_online import *
2
+
3
+ class SpeechRecognizer():
4
+ def __init__(self, language: str, model: str) -> None:
5
+ self.transcribtion_buffer = []
6
+ self.src_lan = language
7
+ asr = FasterWhisperASR(self.src_lan, model)
8
+ asr.use_vad()
9
+ tokenizer = MosesTokeniserWrapper()
10
+ self.processor = VACOnlineASRProcessor(online_chunk_size=1, asr=asr, tokenizer=tokenizer, buffer_trimming=("segment", 15))
11
+
12
+ def append_audio(self, audio: bytes):
13
+ if (len(audio) < 160):
14
+ raise Exception("Chunk is too small (need to be at least 160 bytes)")
15
+
16
+ self.processor.insert_audio_chunk(self.audio_to_tensor(audio))
17
+
18
+ def buffer_size(self):
19
+ return self.processor.online_chunk_size
20
+
21
+ def process_buffer(self):
22
+ return self.processor.process_iter()
23
+
24
+ def flush(self):
25
+ return self.processor.finish()
26
+
27
+ def clear_buffer(self):
28
+ self.transcribtion_buffer.clear()
29
+
30
+ def get_status(self):
31
+ return self.processor.status
32
+
33
+ def audio_to_tensor(self, audio_frame: bytes):
34
+ buffer = np.frombuffer(audio_frame, dtype=np.int16).astype(np.float32) / 32767.0
35
+ return torch.from_numpy(buffer)
36
+
37
+ import re
38
+ class MosesTokeniserWrapper:
39
+ def __init__(self):
40
+ pass
41
+
42
+ def split(self, text):
43
+ rx = r"[^()\s]+|[()]"
44
+ return re.findall(rx, text)
modules/models/whisper_online.py ADDED
@@ -0,0 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ @lru_cache
17
+ def load_audio(fname):
18
+ a, _ = librosa.load(fname, sr=16000, dtype=np.float32)
19
+ return a
20
+
21
+ def load_audio_chunk(fname, beg, end):
22
+ audio = load_audio(fname)
23
+ beg_s = int(beg*16000)
24
+ end_s = int(end*16000)
25
+ return audio[beg_s:end_s]
26
+
27
+
28
+ # Whisper backend
29
+
30
+ class ASRBase:
31
+
32
+ sep = " " # join transcribe words with this character (" " for whisper_timestamped,
33
+ # "" for faster-whisper because it emits the spaces when neeeded)
34
+
35
+ def __init__(self, lan, modelsize=None, cache_dir=None, model_dir=None, logfile=sys.stderr):
36
+ self.logfile = logfile
37
+
38
+ self.transcribe_kargs = {}
39
+ if lan == "auto":
40
+ self.original_language = None
41
+ else:
42
+ self.original_language = lan
43
+
44
+ self.model = self.load_model(modelsize, cache_dir, model_dir)
45
+
46
+
47
+ def load_model(self, modelsize, cache_dir):
48
+ raise NotImplemented("must be implemented in the child class")
49
+
50
+ def transcribe(self, audio, init_prompt=""):
51
+ raise NotImplemented("must be implemented in the child class")
52
+
53
+ def use_vad(self):
54
+ raise NotImplemented("must be implemented in the child class")
55
+
56
+
57
+ class WhisperTimestampedASR(ASRBase):
58
+ """Uses whisper_timestamped library as the backend. Initially, we tested the code on this backend. It worked, but slower than faster-whisper.
59
+ On the other hand, the installation for GPU could be easier.
60
+ """
61
+
62
+ sep = " "
63
+
64
+ def load_model(self, modelsize=None, cache_dir=None, model_dir=None):
65
+ import whisper
66
+ import whisper_timestamped
67
+ from whisper_timestamped import transcribe_timestamped
68
+ self.transcribe_timestamped = transcribe_timestamped
69
+ if model_dir is not None:
70
+ logger.debug("ignoring model_dir, not implemented")
71
+ return whisper.load_model(modelsize, download_root=cache_dir)
72
+
73
+ def transcribe(self, audio, init_prompt=""):
74
+ result = self.transcribe_timestamped(self.model,
75
+ audio, language=self.original_language,
76
+ initial_prompt=init_prompt, verbose=None,
77
+ condition_on_previous_text=True, **self.transcribe_kargs)
78
+ return result
79
+
80
+ def ts_words(self,r):
81
+ # return: transcribe result object to [(beg,end,"word1"), ...]
82
+ o = []
83
+ for s in r["segments"]:
84
+ for w in s["words"]:
85
+ t = (w["start"],w["end"],w["text"])
86
+ o.append(t)
87
+ return o
88
+
89
+ def segments_end_ts(self, res):
90
+ return [s["end"] for s in res["segments"]]
91
+
92
+ def use_vad(self):
93
+ self.transcribe_kargs["vad"] = True
94
+
95
+ def set_translate_task(self):
96
+ self.transcribe_kargs["task"] = "translate"
97
+
98
+
99
+
100
+
101
+ class FasterWhisperASR(ASRBase):
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
+ if model_dir is not None:
111
+ logger.debug(f"Loading whisper model from model_dir {model_dir}. modelsize and cache_dir parameters are not used.")
112
+ model_size_or_path = model_dir
113
+ elif modelsize is not None:
114
+ model_size_or_path = modelsize
115
+ else:
116
+ raise ValueError("modelsize or model_dir parameter must be set")
117
+
118
+ if torch.cuda.is_available():
119
+ model = WhisperModel(model_size_or_path, device="cuda", compute_type="float16", download_root=cache_dir)
120
+ else:
121
+ model = WhisperModel(model_size_or_path, device="cpu", compute_type="int8", download_root=cache_dir)
122
+ # CPU with INT8
123
+ # tested: works, but slow, appx 10-times than cuda FP16
124
+ #model = WhisperModel(modelsize, device="cpu", compute_type="int8", download_root=cache_dir) #, download_root="faster-disk-cache-dir/")
125
+
126
+ # this worked fast and reliably on NVIDIA L40
127
+ # model = WhisperModel(model_size_or_path, device="cuda", compute_type="float16", download_root=cache_dir) БЫЛО
128
+
129
+ # GPU with INT8
130
+ # tested: the transcripts were different, probably worse than with FP16, and it was slightly (appx 20%) slower
131
+ #model = WhisperModel(model_size, device="cuda", compute_type="int8_float16")
132
+ return model
133
+
134
+ def transcribe(self, audio, init_prompt=""):
135
+
136
+ # tested: beam_size=5 is faster and better than 1 (on one 200 second document from En ESIC, min chunk 0.01)
137
+ segments, info = self.model.transcribe(audio, language=self.original_language, initial_prompt=init_prompt, beam_size=5, word_timestamps=True, condition_on_previous_text=True, **self.transcribe_kargs)
138
+ #print(info) # info contains language detection result
139
+
140
+ return list(segments)
141
+
142
+ def ts_words(self, segments):
143
+ o = []
144
+ for segment in segments:
145
+ for word in segment.words:
146
+ if segment.no_speech_prob > 0.9:
147
+ continue
148
+ # not stripping the spaces -- should not be merged with them!
149
+ w = word.word
150
+ t = (word.start, word.end, w)
151
+ o.append(t)
152
+ return o
153
+
154
+ def segments_end_ts(self, res):
155
+ return [s.end for s in res]
156
+
157
+ def use_vad(self):
158
+ self.transcribe_kargs["vad_filter"] = True
159
+
160
+ def set_translate_task(self):
161
+ self.transcribe_kargs["task"] = "translate"
162
+
163
+
164
+ class OpenaiApiASR(ASRBase):
165
+ """Uses OpenAI's Whisper API for audio transcription."""
166
+
167
+ def __init__(self, lan=None, temperature=0, logfile=sys.stderr):
168
+ self.logfile = logfile
169
+
170
+ self.modelname = "whisper-1"
171
+ self.original_language = None if lan == "auto" else lan # ISO-639-1 language code
172
+ self.response_format = "verbose_json"
173
+ self.temperature = temperature
174
+
175
+ self.load_model()
176
+
177
+ self.use_vad_opt = False
178
+
179
+ # reset the task in set_translate_task
180
+ self.task = "transcribe"
181
+
182
+ def load_model(self, *args, **kwargs):
183
+ from openai import OpenAI
184
+ self.client = OpenAI()
185
+
186
+ self.transcribed_seconds = 0 # for logging how many seconds were processed by API, to know the cost
187
+
188
+
189
+ def ts_words(self, segments):
190
+ no_speech_segments = []
191
+ if self.use_vad_opt:
192
+ for segment in segments.segments:
193
+ # TODO: threshold can be set from outside
194
+ if segment["no_speech_prob"] > 0.8:
195
+ no_speech_segments.append((segment.get("start"), segment.get("end")))
196
+
197
+ o = []
198
+ for word in segments.words:
199
+ start = word.get("start")
200
+ end = word.get("end")
201
+ if any(s[0] <= start <= s[1] for s in no_speech_segments):
202
+ # print("Skipping word", word.get("word"), "because it's in a no-speech segment")
203
+ continue
204
+ o.append((start, end, word.get("word")))
205
+ return o
206
+
207
+
208
+ def segments_end_ts(self, res):
209
+ return [s["end"] for s in res.words]
210
+
211
+ def transcribe(self, audio_data, prompt=None, *args, **kwargs):
212
+ # Write the audio data to a buffer
213
+ buffer = io.BytesIO()
214
+ buffer.name = "temp.wav"
215
+ sf.write(buffer, audio_data, samplerate=16000, format='WAV', subtype='PCM_16')
216
+ buffer.seek(0) # Reset buffer's position to the beginning
217
+
218
+ self.transcribed_seconds += math.ceil(len(audio_data)/16000) # it rounds up to the whole seconds
219
+
220
+ params = {
221
+ "model": self.modelname,
222
+ "file": buffer,
223
+ "response_format": self.response_format,
224
+ "temperature": self.temperature,
225
+ "timestamp_granularities": ["word", "segment"]
226
+ }
227
+ if self.task != "translate" and self.original_language:
228
+ params["language"] = self.original_language
229
+ if prompt:
230
+ params["prompt"] = prompt
231
+
232
+ if self.task == "translate":
233
+ proc = self.client.audio.translations
234
+ else:
235
+ proc = self.client.audio.transcriptions
236
+
237
+ # Process transcription/translation
238
+ transcript = proc.create(**params)
239
+ logger.debug(f"OpenAI API processed accumulated {self.transcribed_seconds} seconds")
240
+
241
+ return transcript
242
+
243
+ def use_vad(self):
244
+ self.use_vad_opt = True
245
+
246
+ def set_translate_task(self):
247
+ self.task = "translate"
248
+
249
+
250
+
251
+
252
+ class HypothesisBuffer:
253
+
254
+ def __init__(self, logfile=sys.stderr):
255
+ self.commited_in_buffer = []
256
+ self.buffer = []
257
+ self.new = []
258
+
259
+ self.last_commited_time = 0
260
+ self.last_commited_word = None
261
+
262
+ self.logfile = logfile
263
+
264
+ def insert(self, new, offset):
265
+ # 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
266
+ # the new tail is added to self.new
267
+
268
+ new = [(a+offset,b+offset,t) for a,b,t in new]
269
+ self.new = [(a,b,t) for a,b,t in new if a > self.last_commited_time-0.1]
270
+
271
+ if len(self.new) >= 1:
272
+ a,b,t = self.new[0]
273
+ if abs(a - self.last_commited_time) < 1:
274
+ if self.commited_in_buffer:
275
+ # 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.
276
+ cn = len(self.commited_in_buffer)
277
+ nn = len(self.new)
278
+ for i in range(1,min(min(cn,nn),5)+1): # 5 is the maximum
279
+ c = " ".join([self.commited_in_buffer[-j][2] for j in range(1,i+1)][::-1])
280
+ tail = " ".join(self.new[j-1][2] for j in range(1,i+1))
281
+ if c == tail:
282
+ words = []
283
+ for j in range(i):
284
+ words.append(repr(self.new.pop(0)))
285
+ words_msg = " ".join(words)
286
+ logger.debug(f"removing last {i} words: {words_msg}")
287
+ break
288
+
289
+ def flush(self):
290
+ # returns commited chunk = the longest common prefix of 2 last inserts.
291
+
292
+ commit = []
293
+ while self.new:
294
+ na, nb, nt = self.new[0]
295
+
296
+ if len(self.buffer) == 0:
297
+ break
298
+
299
+ if nt == self.buffer[0][2]:
300
+ commit.append((na,nb,nt))
301
+ self.last_commited_word = nt
302
+ self.last_commited_time = nb
303
+ self.buffer.pop(0)
304
+ self.new.pop(0)
305
+ else:
306
+ break
307
+ self.buffer = self.new
308
+ self.new = []
309
+ self.commited_in_buffer.extend(commit)
310
+ return commit
311
+
312
+ def pop_commited(self, time):
313
+ while self.commited_in_buffer and self.commited_in_buffer[0][1] <= time:
314
+ self.commited_in_buffer.pop(0)
315
+
316
+ def complete(self):
317
+ return self.buffer
318
+
319
+ class OnlineASRProcessor:
320
+
321
+ SAMPLING_RATE = 16000
322
+
323
+ def __init__(self, asr, tokenizer=None, buffer_trimming=("segment", 15), logfile=sys.stderr):
324
+ """asr: WhisperASR object
325
+ 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.
326
+ ("segment", 15)
327
+ 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.
328
+ logfile: where to store the log.
329
+ """
330
+ self.asr = asr
331
+ self.tokenizer = tokenizer
332
+ self.logfile = logfile
333
+
334
+ self.init()
335
+
336
+ self.buffer_trimming_way, self.buffer_trimming_sec = buffer_trimming
337
+
338
+ def init(self, offset=None):
339
+ """run this when starting or restarting processing"""
340
+ self.audio_buffer = np.array([],dtype=np.float32)
341
+ self.transcript_buffer = HypothesisBuffer(logfile=self.logfile)
342
+ self.buffer_time_offset = 0
343
+ if offset is not None:
344
+ self.buffer_time_offset = offset
345
+ self.transcript_buffer.last_commited_time = self.buffer_time_offset
346
+ self.commited = []
347
+
348
+ def insert_audio_chunk(self, audio):
349
+ self.audio_buffer = np.append(self.audio_buffer, audio)
350
+
351
+ def prompt(self):
352
+ """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.
353
+ "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.
354
+ """
355
+ k = max(0,len(self.commited)-1)
356
+ while k > 0 and self.commited[k-1][1] > self.buffer_time_offset:
357
+ k -= 1
358
+
359
+ p = self.commited[:k]
360
+ p = [t for _,_,t in p]
361
+ prompt = []
362
+ l = 0
363
+ while p and l < 200: # 200 characters prompt size
364
+ x = p.pop(-1)
365
+ l += len(x)+1
366
+ prompt.append(x)
367
+ non_prompt = self.commited[k:]
368
+ return self.asr.sep.join(prompt[::-1]), self.asr.sep.join(t for _,_,t in non_prompt)
369
+
370
+ def process_iter(self):
371
+ """Runs on the current audio buffer.
372
+ Returns: a tuple (beg_timestamp, end_timestamp, "text"), or (None, None, "").
373
+ The non-emty text is confirmed (committed) partial transcript.
374
+ """
375
+
376
+ prompt, non_prompt = self.prompt()
377
+ logger.debug(f"PROMPT: {prompt}")
378
+ logger.debug(f"CONTEXT: {non_prompt}")
379
+ logger.debug(f"transcribing {len(self.audio_buffer)/self.SAMPLING_RATE:2.2f} seconds from {self.buffer_time_offset:2.2f}")
380
+ res = self.asr.transcribe(self.audio_buffer, init_prompt=prompt)
381
+
382
+ # transform to [(beg,end,"word1"), ...]
383
+ tsw = self.asr.ts_words(res)
384
+
385
+ self.transcript_buffer.insert(tsw, self.buffer_time_offset)
386
+ o = self.transcript_buffer.flush()
387
+ self.commited.extend(o)
388
+ completed = self.to_flush(o)
389
+ logger.debug(f">>>>COMPLETE NOW: {completed}")
390
+ the_rest = self.to_flush(self.transcript_buffer.complete())
391
+ logger.debug(f"INCOMPLETE: {the_rest}")
392
+
393
+ # there is a newly confirmed text
394
+
395
+ if o and self.buffer_trimming_way == "sentence": # trim the completed sentences
396
+ if len(self.audio_buffer)/self.SAMPLING_RATE > self.buffer_trimming_sec: # longer than this
397
+ self.chunk_completed_sentence()
398
+
399
+
400
+ if self.buffer_trimming_way == "segment":
401
+ s = self.buffer_trimming_sec # trim the completed segments longer than s,
402
+ else:
403
+ s = 30 # if the audio buffer is longer than 30s, trim it
404
+
405
+ if len(self.audio_buffer)/self.SAMPLING_RATE > s:
406
+ self.chunk_completed_segment(res)
407
+
408
+ # alternative: on any word
409
+ #l = self.buffer_time_offset + len(self.audio_buffer)/self.SAMPLING_RATE - 10
410
+ # let's find commited word that is less
411
+ #k = len(self.commited)-1
412
+ #while k>0 and self.commited[k][1] > l:
413
+ # k -= 1
414
+ #t = self.commited[k][1]
415
+ logger.debug("chunking segment")
416
+ #self.chunk_at(t)
417
+
418
+ logger.debug(f"len of buffer now: {len(self.audio_buffer)/self.SAMPLING_RATE:2.2f}")
419
+ return self.to_flush(o)
420
+
421
+ def chunk_completed_sentence(self):
422
+ if self.commited == []: return
423
+ logger.debug(self.commited)
424
+ sents = self.words_to_sentences(self.commited)
425
+ for s in sents:
426
+ logger.debug(f"\t\tSENT: {s}")
427
+ if len(sents) < 2:
428
+ return
429
+ while len(sents) > 2:
430
+ sents.pop(0)
431
+ # we will continue with audio processing at this timestamp
432
+ chunk_at = sents[-2][1]
433
+
434
+ logger.debug(f"--- sentence chunked at {chunk_at:2.2f}")
435
+ self.chunk_at(chunk_at)
436
+
437
+ def chunk_completed_segment(self, res):
438
+ if self.commited == []: return
439
+
440
+ ends = self.asr.segments_end_ts(res)
441
+
442
+ t = self.commited[-1][1]
443
+
444
+ if len(ends) > 1:
445
+
446
+ e = ends[-2]+self.buffer_time_offset
447
+ while len(ends) > 2 and e > t:
448
+ ends.pop(-1)
449
+ e = ends[-2]+self.buffer_time_offset
450
+ if e <= t:
451
+ logger.debug(f"--- segment chunked at {e:2.2f}")
452
+ self.chunk_at(e)
453
+ else:
454
+ logger.debug(f"--- last segment not within commited area")
455
+ else:
456
+ logger.debug(f"--- not enough segments to chunk")
457
+
458
+
459
+
460
+
461
+
462
+ def chunk_at(self, time):
463
+ """trims the hypothesis and audio buffer at "time"
464
+ """
465
+ self.transcript_buffer.pop_commited(time)
466
+ cut_seconds = time - self.buffer_time_offset
467
+ self.audio_buffer = self.audio_buffer[int(cut_seconds*self.SAMPLING_RATE):]
468
+ self.buffer_time_offset = time
469
+
470
+ def words_to_sentences(self, words):
471
+ """Uses self.tokenizer for sentence segmentation of words.
472
+ Returns: [(beg,end,"sentence 1"),...]
473
+ """
474
+
475
+ cwords = [w for w in words]
476
+ t = " ".join(o[2] for o in cwords)
477
+ s = self.tokenizer.split(t)
478
+ out = []
479
+ while s:
480
+ beg = None
481
+ end = None
482
+ sent = s.pop(0).strip()
483
+ fsent = sent
484
+ while cwords:
485
+ b,e,w = cwords.pop(0)
486
+ w = w.strip()
487
+ if beg is None and sent.startswith(w):
488
+ beg = b
489
+ elif end is None and sent == w:
490
+ end = e
491
+ out.append((beg,end,fsent))
492
+ break
493
+ sent = sent[len(w):].strip()
494
+ return out
495
+
496
+ def finish(self):
497
+ """Flush the incomplete text when the whole processing ends.
498
+ Returns: the same format as self.process_iter()
499
+ """
500
+ o = self.transcript_buffer.complete()
501
+ f = self.to_flush(o)
502
+ logger.debug(f"last, noncommited: {f}")
503
+ self.buffer_time_offset += len(self.audio_buffer)/16000
504
+ return f
505
+
506
+
507
+ def to_flush(self, sents, sep=None, offset=0, ):
508
+ # concatenates the timestamped words or sentences into one sequence that is flushed in one line
509
+ # sents: [(beg1, end1, "sentence1"), ...] or [] if empty
510
+ # return: (beg1,end-of-last-sentence,"concatenation of sentences") or (None, None, "") if empty
511
+ if sep is None:
512
+ sep = self.asr.sep
513
+ t = sep.join(s[2] for s in sents)
514
+ if len(sents) == 0:
515
+ b = None
516
+ e = None
517
+ else:
518
+ b = offset + sents[0][0]
519
+ e = offset + sents[-1][1]
520
+ return (b,e,t)
521
+
522
+ class VACOnlineASRProcessor(OnlineASRProcessor):
523
+ '''Wraps OnlineASRProcessor with VAC (Voice Activity Controller).
524
+
525
+ It works the same way as OnlineASRProcessor: it receives chunks of audio (e.g. 0.04 seconds),
526
+ it runs VAD and continuously detects whether there is speech or not.
527
+ When it detects end of speech (non-voice for 500ms), it makes OnlineASRProcessor to end the utterance immediately.
528
+ '''
529
+
530
+ def __init__(self, online_chunk_size, *a, **kw):
531
+ self.online_chunk_size = online_chunk_size
532
+
533
+ self.online = OnlineASRProcessor(*a, **kw)
534
+
535
+ # VAC:
536
+ import torch
537
+ model, _ = torch.hub.load(
538
+ repo_or_dir='snakers4/silero-vad:v4.0',
539
+ model='silero_vad'
540
+ )
541
+ from silero_vad import VADIterator
542
+ self.vac = VADIterator(model, min_silence_duration_ms=1000)
543
+
544
+ self.logfile = self.online.logfile
545
+ self.init()
546
+
547
+ def init(self):
548
+ self.online.init()
549
+ self.vac.reset_states()
550
+ self.current_online_chunk_buffer_size = 0
551
+
552
+ self.is_currently_final = False
553
+
554
+ self.status = None # or "voice" or "nonvoice"
555
+ self.lastStatus = None
556
+ self.audio_buffer = np.array([],dtype=np.float32)
557
+ self.buffer_offset = 0 # in frames
558
+
559
+ def clear_buffer(self):
560
+ self.buffer_offset += len(self.audio_buffer)
561
+ self.audio_buffer = np.array([],dtype=np.float32)
562
+
563
+
564
+ def insert_audio_chunk(self, audio):
565
+ res = self.vac(audio)
566
+ self.audio_buffer = np.append(self.audio_buffer, audio)
567
+ if res is not None:
568
+ frame = list(res.values())[0]
569
+ if 'start' in res and 'end' not in res:
570
+ self.status = 'voice'
571
+ send_audio = self.audio_buffer[frame-self.buffer_offset:]
572
+ self.online.init(offset=frame/self.SAMPLING_RATE)
573
+ self.online.insert_audio_chunk(send_audio)
574
+ self.current_online_chunk_buffer_size += len(send_audio)
575
+ self.clear_buffer()
576
+ elif 'end' in res and 'start' not in res:
577
+ self.status = 'nonvoice'
578
+ send_audio = self.audio_buffer[:frame-self.buffer_offset]
579
+ self.online.insert_audio_chunk(send_audio)
580
+ self.current_online_chunk_buffer_size += len(send_audio)
581
+ self.is_currently_final = True
582
+ self.clear_buffer()
583
+ else:
584
+ # It doesn't happen in the current code.
585
+ raise NotImplemented("both start and end of voice in one chunk!!!")
586
+ else:
587
+ if self.status == 'voice':
588
+ self.online.insert_audio_chunk(self.audio_buffer)
589
+ self.current_online_chunk_buffer_size += len(self.audio_buffer)
590
+ self.clear_buffer()
591
+ else:
592
+ # We keep 1 second because VAD may later find start of voice in it.
593
+ # But we trim it to prevent OOM.
594
+ self.buffer_offset += max(0,len(self.audio_buffer)-self.SAMPLING_RATE)
595
+ self.audio_buffer = self.audio_buffer[-self.SAMPLING_RATE:]
596
+
597
+
598
+ def process_iter(self):
599
+ if self.is_currently_final:
600
+ return self.finish()
601
+ elif self.current_online_chunk_buffer_size > self.SAMPLING_RATE*self.online_chunk_size:
602
+ self.current_online_chunk_buffer_size = 0
603
+ ret = self.online.process_iter()
604
+ return ret
605
+ else:
606
+ if self.status != self.lastStatus:
607
+ print("VAD status changed", self.status, file=self.logfile)
608
+ self.lastStatus = self.status
609
+ return (None, None, "")
610
+
611
+ def finish(self):
612
+ ret = self.online.finish()
613
+ self.current_online_chunk_buffer_size = 0
614
+ self.is_currently_final = False
615
+ return ret
616
+
617
+
618
+
619
+ 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(",")
620
+
621
+ def create_tokenizer(lan):
622
+ """returns an object that has split function that works like the one of MosesTokenizer"""
623
+
624
+ assert lan in WHISPER_LANG_CODES, "language must be Whisper's supported lang code: " + " ".join(WHISPER_LANG_CODES)
625
+
626
+ if lan == "uk":
627
+ import tokenize_uk
628
+ class UkrainianTokenizer:
629
+ def split(self, text):
630
+ return tokenize_uk.tokenize_sents(text)
631
+ return UkrainianTokenizer()
632
+
633
+ # supported by fast-mosestokenizer
634
+ 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():
635
+ from mosestokenizer import MosesTokenizer
636
+ return MosesTokenizer(lan)
637
+
638
+ # the following languages are in Whisper, but not in wtpsplit:
639
+ 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():
640
+ logger.debug(f"{lan} code is not supported by wtpsplit. Going to use None lang_code option.")
641
+ lan = None
642
+
643
+ from wtpsplit import WtP
644
+ # downloads the model from huggingface on the first use
645
+ wtp = WtP("wtp-canine-s-12l-no-adapters")
646
+ class WtPtok:
647
+ def split(self, sent):
648
+ return wtp.split(sent, lang_code=lan)
649
+ return WtPtok()
650
+
651
+
652
+ def add_shared_args(parser):
653
+ """shared args for simulation (this entry point) and server
654
+ parser: argparse.ArgumentParser object
655
+ """
656
+ parser.add_argument('--min-chunk-size', type=float, default=1.0, 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.')
657
+ parser.add_argument('--model', type=str, default='large-v2', choices="tiny.en,tiny,base.en,base,small.en,small,medium.en,medium,large-v1,large-v2,large-v3,large".split(","),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.")
658
+ parser.add_argument('--model_cache_dir', type=str, default=None, help="Overriding the default model cache dir where models downloaded from the hub are saved")
659
+ parser.add_argument('--model_dir', type=str, default=None, help="Dir where Whisper model.bin and other files are saved. This option overrides --model and --model_cache_dir parameter.")
660
+ parser.add_argument('--lan', '--language', type=str, default='auto', help="Source language code, e.g. en,de,cs, or 'auto' for language detection.")
661
+ parser.add_argument('--task', type=str, default='transcribe', choices=["transcribe","translate"],help="Transcribe or translate.")
662
+ parser.add_argument('--backend', type=str, default="faster-whisper", choices=["faster-whisper", "whisper_timestamped", "openai-api"],help='Load only this backend for Whisper processing.')
663
+ parser.add_argument('--vac', action="store_true", default=False, help='Use VAC = voice activity controller. Recommended. Requires torch.')
664
+ parser.add_argument('--vac-chunk-size', type=float, default=0.04, help='VAC sample size in seconds.')
665
+ parser.add_argument('--vad', action="store_true", default=False, help='Use VAD = voice activity detection, with the default parameters.')
666
+ parser.add_argument('--buffer_trimming', type=str, default="segment", choices=["sentence", "segment"],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.')
667
+ parser.add_argument('--buffer_trimming_sec', type=float, default=15, help='Buffer trimming length threshold in seconds. If buffer length is longer, trimming sentence/segment is triggered.')
668
+ parser.add_argument("-l", "--log-level", dest="log_level", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the log level", default='DEBUG')
669
+
670
+ def asr_factory(args, logfile=sys.stderr):
671
+ """
672
+ Creates and configures an ASR and ASR Online instance based on the specified backend and arguments.
673
+ """
674
+ backend = args.backend
675
+ if backend == "openai-api":
676
+ logger.debug("Using OpenAI API.")
677
+ asr = OpenaiApiASR(lan=args.lan)
678
+ else:
679
+ if backend == "faster-whisper":
680
+ asr_cls = FasterWhisperASR
681
+ else:
682
+ asr_cls = WhisperTimestampedASR
683
+
684
+ # Only for FasterWhisperASR and WhisperTimestampedASR
685
+ size = args.model
686
+ t = time.time()
687
+ logger.info(f"Loading Whisper {size} model for {args.lan}...")
688
+ asr = asr_cls(modelsize=size, lan=args.lan, cache_dir=args.model_cache_dir, model_dir=args.model_dir)
689
+ e = time.time()
690
+ logger.info(f"done. It took {round(e-t,2)} seconds.")
691
+
692
+ # Apply common configurations
693
+ if getattr(args, 'vad', False): # Checks if VAD argument is present and True
694
+ logger.info("Setting VAD filter")
695
+ asr.use_vad()
696
+
697
+ language = args.lan
698
+ if args.task == "translate":
699
+ asr.set_translate_task()
700
+ tgt_language = "en" # Whisper translates into English
701
+ else:
702
+ tgt_language = language # Whisper transcribes in this language
703
+
704
+ # Create the tokenizer
705
+ if args.buffer_trimming == "sentence":
706
+ tokenizer = create_tokenizer(tgt_language)
707
+ else:
708
+ tokenizer = None
709
+
710
+ # Create the OnlineASRProcessor
711
+ if args.vac:
712
+
713
+ online = VACOnlineASRProcessor(args.min_chunk_size, asr,tokenizer,logfile=logfile,buffer_trimming=(args.buffer_trimming, args.buffer_trimming_sec))
714
+ else:
715
+ online = OnlineASRProcessor(asr,tokenizer,logfile=logfile,buffer_trimming=(args.buffer_trimming, args.buffer_trimming_sec))
716
+
717
+ return asr, online
718
+
719
+ def set_logging(args,logger,other="_server"):
720
+ logging.basicConfig(#format='%(name)s
721
+ format='%(levelname)s\t%(message)s')
722
+ logger.setLevel(args.log_level)
723
+ logging.getLogger("whisper_online"+other).setLevel(args.log_level)
724
+ # logging.getLogger("whisper_online_server").setLevel(args.log_level)
725
+
726
+
727
+
728
+ if __name__ == "__main__":
729
+
730
+ import argparse
731
+ parser = argparse.ArgumentParser()
732
+ parser.add_argument('audio_path', type=str, help="Filename of 16kHz mono channel wav, on which live streaming is simulated.")
733
+ add_shared_args(parser)
734
+ parser.add_argument('--start_at', type=float, default=0.0, help='Start processing audio at this time.')
735
+ parser.add_argument('--offline', action="store_true", default=False, help='Offline mode.')
736
+ parser.add_argument('--comp_unaware', action="store_true", default=False, help='Computationally unaware simulation.')
737
+
738
+ args = parser.parse_args()
739
+
740
+ # reset to store stderr to different file stream, e.g. open(os.devnull,"w")
741
+ logfile = sys.stderr
742
+
743
+ if args.offline and args.comp_unaware:
744
+ logger.error("No or one option from --offline and --comp_unaware are available, not both. Exiting.")
745
+ sys.exit(1)
746
+
747
+ # if args.log_level:
748
+ # logging.basicConfig(format='whisper-%(levelname)s:%(name)s: %(message)s',
749
+ # level=getattr(logging, args.log_level))
750
+
751
+ set_logging(args,logger)
752
+
753
+ audio_path = args.audio_path
754
+
755
+ SAMPLING_RATE = 16000
756
+ duration = len(load_audio(audio_path))/SAMPLING_RATE
757
+ logger.info("Audio duration is: %2.2f seconds" % duration)
758
+
759
+ asr, online = asr_factory(args, logfile=logfile)
760
+ if args.vac:
761
+ min_chunk = args.vac_chunk_size
762
+ else:
763
+ min_chunk = args.min_chunk_size
764
+
765
+ # load the audio into the LRU cache before we start the timer
766
+ a = load_audio_chunk(audio_path,0,1)
767
+
768
+ # warm up the ASR because the very first transcribe takes much more time than the other
769
+ asr.transcribe(a)
770
+
771
+ beg = args.start_at
772
+ start = time.time()-beg
773
+
774
+ def output_transcript(o, now=None):
775
+ # output format in stdout is like:
776
+ # 4186.3606 0 1720 Takhle to je
777
+ # - the first three words are:
778
+ # - emission time from beginning of processing, in milliseconds
779
+ # - beg and end timestamp of the text segment, as estimated by Whisper model. The timestamps are not accurate, but they're useful anyway
780
+ # - the next words: segment transcript
781
+ if now is None:
782
+ now = time.time()-start
783
+ if o[0] is not None:
784
+ print("%1.4f %1.0f %1.0f %s" % (now*1000, o[0]*1000,o[1]*1000,o[2]),file=logfile,flush=True)
785
+ print("%1.4f %1.0f %1.0f %s" % (now*1000, o[0]*1000,o[1]*1000,o[2]),flush=True)
786
+ else:
787
+ # No text, so no output
788
+ pass
789
+
790
+ if args.offline: ## offline mode processing (for testing/debugging)
791
+ a = load_audio(audio_path)
792
+ online.insert_audio_chunk(a)
793
+ try:
794
+ o = online.process_iter()
795
+ except AssertionError as e:
796
+ logger.error(f"assertion error: {repr(e)}")
797
+ else:
798
+ output_transcript(o)
799
+ now = None
800
+ elif args.comp_unaware: # computational unaware mode
801
+ end = beg + min_chunk
802
+ while True:
803
+ a = load_audio_chunk(audio_path,beg,end)
804
+ online.insert_audio_chunk(a)
805
+ try:
806
+ o = online.process_iter()
807
+ except AssertionError as e:
808
+ logger.error(f"assertion error: {repr(e)}")
809
+ pass
810
+ else:
811
+ output_transcript(o, now=end)
812
+
813
+ logger.debug(f"## last processed {end:.2f}s")
814
+
815
+ if end >= duration:
816
+ break
817
+
818
+ beg = end
819
+
820
+ if end + min_chunk > duration:
821
+ end = duration
822
+ else:
823
+ end += min_chunk
824
+ now = duration
825
+
826
+ else: # online = simultaneous mode
827
+ end = 0
828
+ while True:
829
+ now = time.time() - start
830
+ if now < end+min_chunk:
831
+ time.sleep(min_chunk+end-now)
832
+ end = time.time() - start
833
+ a = load_audio_chunk(audio_path,beg,end)
834
+ beg = end
835
+ online.insert_audio_chunk(a)
836
+
837
+ try:
838
+ o = online.process_iter()
839
+ except AssertionError as e:
840
+ logger.error(f"assertion error: {e}")
841
+ pass
842
+ else:
843
+ output_transcript(o)
844
+ now = time.time() - start
845
+ logger.debug(f"## last processed {end:.2f} s, now is {now:.2f}, the latency is {now-end:.2f}")
846
+
847
+ if end >= duration:
848
+ break
849
+ now = None
850
+
851
+ o = online.finish()
852
+ output_transcript(o, now=now)
modules/routers/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Depends
2
+ from .transcription import router
3
+
4
+ def setup_routers(app: FastAPI) -> None:
5
+ app.include_router(
6
+ router,
7
+ tags=["WebSockets"],
8
+ prefix="/ws"
9
+ )
modules/routers/transcription.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, WebSocket
2
+ from starlette.websockets import WebSocketState
3
+ from modules.models.speech_recognizer import SpeechRecognizer
4
+ router = APIRouter()
5
+
6
+ @router.websocket("/transcribe")
7
+ async def transcribe_audio(websocket: WebSocket):
8
+ recognizer = SpeechRecognizer("ru", "deepdml/faster-whisper-large-v3-turbo-ct2")
9
+ await websocket.accept()
10
+ message_buffer = ""
11
+ last_status = None
12
+
13
+ try:
14
+ while websocket.client_state == WebSocketState.CONNECTING or websocket.client_state == WebSocketState.CONNECTED:
15
+ try:
16
+ # Receive audio data
17
+ audio = await websocket.receive_bytes()
18
+ recognizer.append_audio(audio)
19
+ recognized_text = recognizer.process_buffer()
20
+ status = recognizer.get_status()
21
+
22
+ # If the status hasn't changed and no new text is recognized, skip to next iteration
23
+ if status == last_status and recognized_text[0] is None:
24
+ continue
25
+
26
+ last_status = status
27
+
28
+ # Handle recognized text based on status
29
+ if status == 'voice':
30
+ message_buffer += recognized_text[2]
31
+ if len(message_buffer) > 0 and not str.isspace(message_buffer):
32
+ print(f"Sending partial message: {message_buffer}")
33
+ obj = {"text": message_buffer, "is_complete": False}
34
+ await websocket.send_json(obj)
35
+ elif status == 'nonvoice':
36
+ message_buffer += recognizer.flush()[2]
37
+ if len(message_buffer) > 0 and not str.isspace(message_buffer):
38
+ print(f"Sending complete message: {message_buffer}")
39
+ obj = {"text": message_buffer, "is_complete": True}
40
+ await websocket.send_json(obj)
41
+ message_buffer = "" # Reset buffer after sending message
42
+ except (RuntimeError, ConnectionError) as e:
43
+ # Catch errors due to disconnection or network issues
44
+ print(f"Client disconnected: {e}")
45
+ break
46
+ except Exception as e:
47
+ print(f"Unexpected error: {e}")
48
+ break
49
+ finally:
50
+ # Ensure proper cleanup even if the loop exits
51
+ recognizer.clear_buffer()
52
+ try:
53
+ await websocket.close()
54
+ except Exception as e:
55
+ print(f"Error closing websocket: {e}")
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi[standard]
2
+ uvicorn[standard]
3
+ librosa==0.10.2
4
+ tokenizers==0.13.3
5
+ faster-whisper==1.1.0
6
+ soundfile==0.13.0
7
+ silero-vad==5.1