File size: 6,382 Bytes
6e5cbb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""Opt-in staging FP16 adapter for our candidates; NCAIR remains the detector and fallback."""
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time

import numpy as np
import soundfile as sf

from .asr_pipeline import TranscriptionResult
from .candidates import CANDIDATES, candidate_lang, ct2_enabled
from .speech_gate import speech_regions


def prepare_model(cache_dir, lang='ha'):
    """Atomic, locked conversion of immutable weights and their own tokenizer."""
    c = CANDIDATES[lang]
    from filelock import FileLock
    from huggingface_hub import snapshot_download
    root = Path(cache_dir) / 'narratifai-ct2'
    root.mkdir(parents=True, exist_ok=True)
    target = root / (c['revision'] + '-fp16-ct2-4.5.0')
    manifest = {'revision': c['revision'], 'repo': c['path'], 'precision': 'float16', 'converter': '4.5.0'}
    with FileLock(str(target) + '.lock', timeout=600):
        marker = target / 'narratifai.json'
        if marker.exists() and json.loads(marker.read_text()) == manifest and all(
                (target / name).is_file() for name in ('model.bin', 'config.json', 'tokenizer.json', 'preprocessor_config.json')):
            return target
        source = snapshot_download(c['path'], revision=c['revision'], cache_dir=cache_dir)
        staging = Path(tempfile.mkdtemp(prefix='convert-', dir=root))
        try:
            # Conversion lives in a child process so its large CPU allocations are freed.
            subprocess.run(['ct2-transformers-converter', '--model', source, '--output_dir', str(staging),
                            '--copy_files', 'preprocessor_config.json', '--quantization', 'float16', '--force'],
                           check=True, timeout=600)
            from transformers import WhisperTokenizerFast
            WhisperTokenizerFast.from_pretrained(source).backend_tokenizer.save(str(staging / 'tokenizer.json'))
            (staging / 'narratifai.json').write_text(json.dumps(manifest))
            if target.exists():
                shutil.rmtree(target)
            staging.rename(target)
        finally:
            if staging.exists():
                shutil.rmtree(staging)
    return target


def preload_cuda_libraries():
    """CTranslate2 links cuBLAS 12 and cuDNN 9 by name. The Space has no system
    CUDA: they come with the Torch wheels (site-packages/nvidia/*/lib), which
    the loader only searches if LD_LIBRARY_PATH said so at process start.
    Loading them globally first lets CTranslate2 find them already loaded."""
    import ctypes
    import site
    import sys
    bases = [b for b in dict.fromkeys(sys.path + site.getsitepackages()) if b]
    loaded = []
    for package in ('cublas', 'cudnn'):
        for base in bases:
            libdir = Path(base) / 'nvidia' / package / 'lib'
            if not libdir.is_dir():
                continue
            # Base libraries before the ones that depend on them.
            names = sorted(libdir.glob('lib*.so*'), key=lambda f: (
                0 if f.name.startswith(('libcublasLt', 'libcudnn.so')) else 1, f.name))
            for lib in names:
                try:
                    ctypes.CDLL(str(lib), mode=ctypes.RTLD_GLOBAL)
                    loaded.append(lib.name)
                except OSError:
                    pass
            break
    return loaded


class CandidateCT2Pipeline:
    def __init__(self, model_key, registry, config):
        self.lang = candidate_lang(model_key)
        if not self.lang:
            raise ValueError('CT2 adapter is restricted to our candidates')
        self.model_key, self.registry, self.config = model_key, registry, config
        self.pipeline = None

    def _initialize_pipeline(self):
        if not ct2_enabled(self.lang):
            raise ValueError('CT2 candidate requires explicit staging flags')
        if self.pipeline is None:
            if self.registry.device.type != 'cuda':
                raise RuntimeError('FP16 candidate requires CUDA')
            self.registry.unload_all_except(self.model_key)
            preload_cuda_libraries()
            from faster_whisper import WhisperModel
            path = prepare_model(self.registry.cache_dir, self.lang)
            self.pipeline = WhisperModel(str(path), device='cuda', compute_type='float16')
            self.registry.current_model = self.model_key

    def close(self):
        if self.pipeline is not None:
            self.pipeline.model.unload_model()
            self.pipeline = None

    def transcribe(self, audio, **kwargs):
        started = time.perf_counter()
        if not ct2_enabled(self.lang):
            raise ValueError('CT2 candidate is disabled')
        if isinstance(audio, (str, Path, bytes)):
            audio, sr = sf.read(io.BytesIO(audio) if isinstance(audio, bytes) else audio, dtype='float32')
            if sr != 16000:
                raise ValueError('Adapter requires 16 kHz audio')
        audio = np.asarray(audio, dtype=np.float32)
        regions = speech_regions(audio)
        segments = []
        if regions:
            self._initialize_pipeline()
        for region in regions:
            begin, end = region['start'], region['end']
            decoded, _ = self.pipeline.transcribe(
                audio[begin:end], language=CANDIDATES[self.lang]['token'], task='transcribe', beam_size=1,
                temperature=(0., .2, .4, .6, .8, 1.), condition_on_previous_text=False,
                vad_filter=False, no_speech_threshold=.6, log_prob_threshold=-1.,
                compression_ratio_threshold=2.4, word_timestamps=False,
            )
            for segment in decoded:
                text = segment.text.strip()
                start = max(begin / 16000, min(end / 16000, begin / 16000 + segment.start))
                stop = max(start, min(end / 16000, begin / 16000 + segment.end))
                if text and stop > start:
                    segments.append({'id': len(segments), 'start': start, 'end': stop, 'text': text})
        return TranscriptionResult(
            text=' '.join(s['text'] for s in segments), language=self.lang, segments=segments,
            model_used=self.model_key, audio_duration=len(audio) / 16000,
            processing_time=time.perf_counter() - started,
        )


HausaCT2Pipeline = CandidateCT2Pipeline   # the first candidate's name