Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

387 deploy whisper #388

Merged
merged 58 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
a539494
add whisper start in docker-compose
arhihihipov Nov 9, 2023
d4a47ec
add env
arhihihipov Nov 23, 2023
5358360
update whisper deploy in docker-compose
arhihihipov Feb 18, 2024
23c579a
add test whisper
arhihihipov Feb 18, 2024
f9d5b9d
add deploy Whisper
arhihihipov Feb 24, 2024
142111c
update whisper test RTF
arhihihipov Feb 24, 2024
3bc3398
Vosk is gone
arhihihipov Feb 25, 2024
9e34833
fixes
arhihihipov Feb 26, 2024
6884eab
add logging
arhihihipov Feb 27, 2024
4301952
update github runner environment
HadronCollider Mar 7, 2024
0a46c88
add hot fix for chrome deb install
HadronCollider Mar 7, 2024
a5af166
update TestPredefenceEightToTenMinutesFeedbackEvaluator for new Prede…
HadronCollider Mar 7, 2024
15c8182
big rework of test_basic_training
HadronCollider Mar 7, 2024
edd5157
use driver.refresh() to reload page
HadronCollider Mar 7, 2024
57aeccd
Decreasing whisper model for github ci (medium->tiny)
HadronCollider Mar 7, 2024
6620f9c
Merge pull request #394 from OSLL/fix-github-ci
HadronCollider Mar 7, 2024
7895f4d
1st step of rework Docker (update wst_base image)
HadronCollider Mar 9, 2024
81763d7
update dockerhub repo and tag for wst_base image in build script
HadronCollider Mar 9, 2024
2b2af94
update requirements (WIP) and fix using updated libs
HadronCollider Mar 9, 2024
7444699
update Dockerfile (rework + new base image + labels) and docker-compo…
HadronCollider Mar 9, 2024
1fb986b
update docker image naming rules
HadronCollider Mar 9, 2024
d84fc9e
update workflow step (building base image)
HadronCollider Mar 9, 2024
7330454
update db_versioning (if no version == LAST_VERSION)
HadronCollider Mar 9, 2024
7ccda4c
move denoiser module from playground
HadronCollider Mar 9, 2024
2525f08
move denoiser module 2.0
HadronCollider Mar 9, 2024
0adc439
set up pythpn requirement versions
HadronCollider Mar 9, 2024
d9c2a9f
update dockerfiles
HadronCollider Mar 9, 2024
f6f707e
disabled wrong test whisper for GitHub workflow
HadronCollider Mar 9, 2024
0a53514
update sh scripts for building base image
HadronCollider Mar 9, 2024
9a92766
rename base image build script
HadronCollider Mar 9, 2024
95624bb
set ASR_MODEL=medium for deploy (before transfer to .env)
HadronCollider Mar 9, 2024
17c68ac
rm ports to whisper service
HadronCollider Mar 9, 2024
1dacb4d
Update test run in GitHub actions
HadronCollider Mar 9, 2024
5728e9c
Update main.yml Run tests
HadronCollider Mar 9, 2024
4bd9c00
update restart.sh (remove apache/ssl setup; update docker build command)
HadronCollider Mar 9, 2024
48fb3f9
add env
arhihihipov Mar 9, 2024
07ee0f6
Merge remote-tracking branch 'origin/whisper_deploy' into whisper_deploy
arhihihipov Mar 9, 2024
2f4cabf
restore vosk and add url param for Whisper
arhihihipov Mar 10, 2024
9740468
add .env to gitignore
arhihihipov Mar 12, 2024
496c079
Delete .env
arhihihipov Mar 12, 2024
034351a
add http errors handling and test whisper plug
arhihihipov Mar 12, 2024
3384b42
Update docker tag in workflow (main)
HadronCollider Mar 12, 2024
234fad6
add whisper cache to gitignore
arhihihipov Mar 14, 2024
45b70dd
merge whisper_deploy
HadronCollider Mar 20, 2024
7e0a4dd
fix comments. Add env variable Mem_Limit, volume. Also increase timeo…
arhihihipov Mar 26, 2024
5dd6866
remove port whisper
arhihihipov Mar 26, 2024
1a901b0
remove convert audio to wav and denoise for whisper
arhihihipov Mar 30, 2024
6af5a48
update test for whisper
arhihihipov Mar 30, 2024
d84ae55
Merge branch 'master' into whisper_deploy
arhihihipov Mar 30, 2024
25f5068
increase waitint time in test
arhihihipov Mar 30, 2024
5be8e9c
increase waitint time in test
arhihihipov Mar 30, 2024
90684a6
Merge branch 'whisper_deploy' of github.com:OSLL/web_speech_trainer i…
arhihihipov Mar 30, 2024
4e91e9f
Revert "increase waitint time in test"
arhihihipov Mar 30, 2024
c82a185
Merge branch 'whisper_deploy' of github.com:OSLL/web_speech_trainer i…
HadronCollider Mar 31, 2024
0dbb056
add local import for websockets (VoskAudioRecognizer)
HadronCollider Mar 31, 2024
fbec381
Merge branch 'master' into update_image
HadronCollider Mar 31, 2024
a67df4f
Merge pull request #399 from OSLL/update_image
HadronCollider Mar 31, 2024
cf032d2
remove excessive log
arhihihipov Apr 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@ jobs:
# build base image
docker build -f Dockerfile_base -t osll/wst_base .

# build vosk
docker build -f "Dockerfile.kaldi-ru" -t osll/vosk .

- name: Build docker-compose
run: |
docker-compose build
Expand Down
15 changes: 0 additions & 15 deletions Dockerfile.kaldi-ru

This file was deleted.

15 changes: 13 additions & 2 deletions app/audio_processor.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import sys
import time
from datetime import datetime

import librosa
from bson import ObjectId

from app.audio_recognizer import AudioRecognizer, VoskAudioRecognizer
from app.audio_recognizer import AudioRecognizer, WhisperAudioRecognizer
from app.config import Config
from app.mongo_models import Trainings
from app.mongo_odm import DBManager, AudioToRecognizeDBManager, TrainingsDBManager, RecognizedAudioToProcessDBManager
Expand Down Expand Up @@ -52,7 +54,16 @@ def _try_extract_and_process(self):
self._hangle_error(training_id, verdict)
return
try:
audio_length = librosa.get_duration(filename=presentation_record_file)
logger.info(f'audio record length: {audio_length} s')

start_time = time.time()

recognized_audio = self._audio_recognizer.recognize(presentation_record_file)

end_time = time.time()
processing_time = end_time - start_time
logger.info(f'audio processing time: {processing_time} s')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавьте в сообщение длительность аудио (вы её получаете выше) - так будут более полезные логи (длина записи + время её обработки)

except Exception as e:
verdict = 'Recognition of a presentation record file with presentation_record_file_id = {} ' \
'has failed.\n{}'.format(presentation_record_file_id, e)
Expand Down Expand Up @@ -118,7 +129,7 @@ def run(self):

if __name__ == "__main__":
Config.init_config(sys.argv[1])
audio_recognizer = VoskAudioRecognizer(host=Config.c.vosk.url)
audio_recognizer = WhisperAudioRecognizer()
audio_processor = AudioProcessor(audio_recognizer)
audio_processor.run()
stuck_audio_resender = StuckAudioResender()
Expand Down
47 changes: 22 additions & 25 deletions app/audio_recognizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
import wave

import websockets
import requests

from app import utils
from app.recognized_audio import RecognizedAudio
Expand All @@ -25,23 +25,17 @@ def recognize(self, audio):
return RecognizedAudio(recognized_words)


class VoskAudioRecognizer(AudioRecognizer):
HadronCollider marked this conversation as resolved.
Show resolved Hide resolved
def __init__(self, host):
self._host = host
self._event_loop = asyncio.get_event_loop()

class WhisperAudioRecognizer(AudioRecognizer):
def parse_recognizer_result(self, recognizer_result):
return RecognizedWord(
word=Word(recognizer_result['word']),
begin_timestamp=recognizer_result['start'],
end_timestamp=recognizer_result['end'],
probability=recognizer_result['conf'],
probability=recognizer_result['probability'],
)

def recognize_wav(self, audio):
recognizer_results = self._event_loop.run_until_complete(
self.send_audio_to_recognizer(audio.name)
)
recognizer_results = self.send_audio_to_recognizer(audio.name)
recognized_words = list(map(self.parse_recognizer_result, recognizer_results))
return RecognizedAudio(recognized_words)

Expand All @@ -50,19 +44,22 @@ def recognize(self, audio):
Denoiser.process_wav_to_wav(temp_wav_file, temp_wav_file, noise_length=3)
return self.recognize_wav(temp_wav_file)

async def send_audio_to_recognizer(self, file_name):
def send_audio_to_recognizer(self, file_name, language='ru'):
url = 'http://whisper:9000/asr'
HadronCollider marked this conversation as resolved.
Show resolved Hide resolved
params = {
'task': 'transcribe',
'language': language,
'word_timestamps': 'true',
'output': 'json'
}
headers = {'accept': 'application/json'}
files = {'audio_file': (file_name, open(file_name, 'rb'), 'audio/mpeg')}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не будет ли проблем с размером файла, если кто-то наговорит на пару часов? (условная 413 client request body or request entity is too large)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не совсем понимаю, как это можно проверить в коде, и нужно ли?
Я немного переписал эту часть кода — добавил закрытие файла после прочтения, теперь посылаю не дескриптор, а буфер, в который файл был считан

Copy link
Collaborator

@HadronCollider HadronCollider Mar 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут скорее вопрос (на исследование/проверку) - какого максимального размера аудио можно отправить в asr?
И можно ли защититься от ошибок со слишком большими файлами (разбивать их на более мелкие / др) - в vosk, например, данные отправлялись кусками по сокету, поэтому теоретически происходила обработка аудио любого размера

Copy link
Collaborator Author

@arhihihipov arhihihipov Mar 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пока что удалось установить, что верхний предел у Whisper всё же существует

  1. 2 часа 15 минут тишины весом в 309 мб удалось обработать
  2. 1 час 30 минут разговорного подкаста весом 213 мб тоже удалось обработать
  3. 2 часа 30 минут тишины весом в 344 мб обработать не удалось -- вышли за лимиты по памяти
    Аудио загружались в tiny модель с характеристиками, указанными по дефолту в docker compose

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вынесите свои исследования в https://github.com/OSLL/web_speech_trainer/wiki

response = requests.post(url, params=params, headers=headers, files=files)

data = response.json()
HadronCollider marked this conversation as resolved.
Show resolved Hide resolved

recognizer_results = []
async with websockets.connect(self._host) as websocket:
wf = wave.open(file_name, "rb")
await websocket.send('''{"config" : { "sample_rate" : 8000.0 }}''')
while True:
data = wf.readframes(1000)
if len(data) == 0:
break
await websocket.send(data)
json_data = json.loads(await websocket.recv())
if 'result' in json_data:
recognizer_results += json_data['result']
await websocket.send('{"eof" : 1}')
await websocket.recv()
return recognizer_results
for segment in data["segments"]:
for recognized_word in segment["words"]:
recognizer_results.append(recognized_word)
return recognizer_results
3 changes: 0 additions & 3 deletions app_conf/config.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ backup_path=../dump/database-dump/
url=mongodb://db:27017/
database_name=database

[vosk]
url=ws://vosk:2700

[user_agent_platform]
windows=True
linux=True
Expand Down
3 changes: 0 additions & 3 deletions app_conf/testing.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ backup_path=../dump/database-dump/
url=mongodb://db:27017/
database_name=testing_database

[vosk]
url=ws://vosk:2700

[testing]
active=True
session_id=testing_session_id
Expand Down
17 changes: 10 additions & 7 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,14 @@ services:
- training_processor
volumes:
- ../database-dump:/app/dump/database-dump/

vosk:
image: "osll/vosk:v0.1"
restart: always
ports:
- 2700:2700

audio_processor:
image: base_image
command: python3 -m audio_processor $APP_CONF
restart: always
depends_on:
- db
- vosk
- whisper
- presentation_processor

recognized_audio_processor:
Expand Down Expand Up @@ -76,3 +70,12 @@ services:
- '--wiredTigerCacheSizeGB=2'
volumes:
- ../mongo_data:/data/db

whisper:
HadronCollider marked this conversation as resolved.
Show resolved Hide resolved
image: "onerahmet/openai-whisper-asr-webservice:latest"
HadronCollider marked this conversation as resolved.
Show resolved Hide resolved
environment:
- ASR_MODEL=medium
- ASR_ENGINE=openai_whisper
HadronCollider marked this conversation as resolved.
Show resolved Hide resolved
restart: always
ports:
- "127.0.0.1:9000:9000"
HadronCollider marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ vext
vext.gi
websockets
wheel
librosa
librosa == 0.9.2
noisereduce == 1.1.0
python_speech_features
pysndfx
python-i18n
python-pptx ==0.6.19
odfpy ==1.4.1
requests ==2.27.1
3 changes: 0 additions & 3 deletions scripts/build_system_image.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,5 @@ set -e

tag=${1:-'v0.1'}

# build vosk
./scripts/build_image.sh "Dockerfile.kaldi-ru" osll/vosk:$tag

# build base image
./scripts/build_image.sh Dockerfile_base osll/wst_base:$tag
32 changes: 32 additions & 0 deletions tests/test_whisper.py
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как вы предполагаете автоматизированный запуск подобного теста?

  • функции тестов для pytest не принимают каких-либо параметров - аргумент "file" передать не удастся
  • для проверки корректности транскрибация нужны две вещи 1) аудио-запись 2) верная транскрибация (для оценки результата работы)
  • у вас есть код, использующий в проекте (class WhisperAudioRecognizer) - тестировать стоит его/через него, а не какой-то код для взаимодействия с whisper (в коде этого файла может не быть проблем, а в том, что используется в системе, задействован в проверках - всё ломается и не работает, к примеру)
    • в конце концов вам необходимо проверить даже не работу самого whisper (это уже делали до вас его создатели и пользователи), а кода, который вы реализовали для взаимодействия с ним, но допустим пока обойдемся без mock

Copy link
Collaborator Author

@arhihihipov arhihihipov Mar 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Соглашусь, такой код для тестирования не подойдёт. Хотелось бы узнать, стоит ли вообще писать тест для Whisper, и если да, то что именно нужно протестировать?

Copy link
Collaborator

@HadronCollider HadronCollider Mar 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавьте тестирование своего класса WhisperAudioRecognizer (пусть даже он частично будет общаться с whisper-контейнером, и это будет уже не совсем unit-тестирование)

  • тестовые аудио есть в /tests - можно сопоставить истинные результаты с возвращаемыми классом (лучше параметризуйте через pytest входной файл и данные)

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image
Возникли трудности с написанием тестов, дело в том, что на данный момент tiny модель "Добрый день, все хорошо. Я сижу дома" распознаёт так, как показано на фото. Первая строка результат распознавания после применений denoiser, перегона в wav, а на второй строке результат распознавания необработанной записи

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давайте пока оставим тесты в том виде в котором есть (с печатью распознанных слов)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А по поводу wav и denoiser - посмотрите, насколько они нужны при работе с whisper (создал задачу - #401 ) - wav нужен был для vosk, возможно, сейчас от него можно избавиться?

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import requests
import time
import librosa

def test_whisper(file):
url = "http://whisper:9000/asr"
params = {
'task': 'transcribe',
'language': 'ru',
'word_timestamps': 'true',
'output': 'json'
}
headers = {'accept': 'application/json'}
print(f"Processing file \"{file}\"")
files = {'audio_file': (file, open(file, 'rb'), 'audio/mpeg')}

audio_length = librosa.get_duration(filename=file)

start_time = time.time()
response = requests.post(url, params=params, headers=headers, files=files)
end_time = time.time()
processing_time = end_time - start_time
RTF = processing_time / audio_length
print(f"RTF = {RTF}")

#parsing
data = response.json()
words = []
for segment in data["segments"]:
for word_structure in segment["words"]:
words.append(word_structure)
print(word_structure)
Loading