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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import logging
import os
import tempfile
import time
from typing import Dict, Iterator, Optional, Tuple

from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.document_loaders.generic import GenericLoader
from langchain.schema import Document

logger = logging.getLogger(__name__)


class OpenAIWhisperParser(BaseBlobParser):
    """Transcribe and parse audio files.
    Audio transcription is with OpenAI Whisper model."""

    def __init__(self, api_key: Optional[str] = None):
        self.api_key = api_key

    def lazy_parse(self, blob: Blob) -> Iterator[Document]:
        """Lazily parse the blob."""

        import io

        try:
            from openai import OpenAI
            if self.api_key:
                client = OpenAI(api_key=self.api_key)
            else:
                client = OpenAI()
        except ImportError:
            raise ImportError(
                "openai package not found, please install it with "
                "`pip install openai`"
            )
        try:
            from pydub import AudioSegment
        except ImportError:
            raise ImportError(
                "pydub package not found, please install it with " "`pip install pydub`"
            )

        # Audio file from disk
        audio = AudioSegment.from_file(blob.path)

        # Define the duration of each chunk in minutes
        # Need to meet 25MB size limit for Whisper API
        chunk_duration = 20
        chunk_duration_ms = chunk_duration * 60 * 1000

        # Split the audio into chunk_duration_ms chunks
        for split_number, i in enumerate(range(0, len(audio), chunk_duration_ms)):
            # Audio chunk
            chunk = audio[i: i + chunk_duration_ms]
            file_obj = io.BytesIO(chunk.export(format="mp3").read())
            if blob.source is not None:
                file_obj.name = blob.source + f"_part_{split_number}.mp3"
            else:
                file_obj.name = f"part_{split_number}.mp3"

            # Transcribe
            print(f"Transcribing part {split_number + 1}!")
            attempts = 0
            while attempts < 3:
                try:
                    transcript = client.audio.transcribe("whisper-1", file_obj)
                    break
                except Exception as e:
                    attempts += 1
                    print(f"Attempt {attempts} failed. Exception: {str(e)}")
                    time.sleep(5)
            else:
                print("Failed to transcribe after 3 attempts.")
                continue

            yield Document(
                page_content=transcript.text,
                metadata={"source": blob.source, "chunk": split_number},
            )


class OpenAIWhisperParserLocal(BaseBlobParser):
    """Transcribe and parse audio files with OpenAI Whisper model.

    Audio transcription with OpenAI Whisper model locally from transformers.

    Parameters:
    device - device to use
        NOTE: By default uses the gpu if available,
        if you want to use cpu, please set device = "cpu"
    lang_model - whisper model to use, for example "openai/whisper-medium"
    forced_decoder_ids - id states for decoder in multilanguage model,
        usage example:
        from transformers import WhisperProcessor
        processor = WhisperProcessor.from_pretrained("openai/whisper-medium")
        forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language="french",
          task="transcribe")
        forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language="french",
        task="translate")



    """

    def __init__(
            self,
            device: str = 'gpu',
            device_id: int = 0,
            lang_model: Optional[str] = None,
            forced_decoder_ids: Optional[Tuple[Dict]] = None,
            use_better=True,
            use_faster=False,
    ):
        """Initialize the parser.

        Args:
            device: device to use.
            lang_model: whisper model to use, for example "openai/whisper-medium".
              Defaults to None.
            forced_decoder_ids: id states for decoder in a multilanguage model.
              Defaults to None.
        """
        try:
            from transformers import pipeline
        except ImportError:
            raise ImportError(
                "transformers package not found, please install it with "
                "`pip install transformers`"
            )
        try:
            import torch
        except ImportError:
            raise ImportError(
                "torch package not found, please install it with " "`pip install torch`"
            )

        # set device, cpu by default check if there is a GPU available
        if device == "cpu":
            self.device = "cpu"
            if lang_model is not None:
                self.lang_model = lang_model
                print("WARNING! Model override. Using model: ", self.lang_model)
            else:
                # unless overridden, use the small base model on cpu
                self.lang_model = "openai/whisper-base"
        else:
            if torch.cuda.is_available():
                self.device = "cuda"
                # check GPU memory and select automatically the model
                mem = torch.cuda.get_device_properties(self.device).total_memory / (
                        1024 ** 2
                )
                if mem < 5000:
                    rec_model = "openai/whisper-base"
                elif mem < 7000:
                    rec_model = "openai/whisper-small"
                elif mem < 12000:
                    rec_model = "openai/whisper-medium"
                else:
                    rec_model = "openai/whisper-large-v3"

                # check if model is overridden
                if lang_model is not None:
                    self.lang_model = lang_model
                    print("WARNING! Model override. Might not fit in your GPU")
                else:
                    self.lang_model = rec_model
            else:
                "cpu"

        print("Using the following model: ", self.lang_model)

        # load model for inference
        if self.device == 'cpu':
            device_map = {"", 'cpu'}
        else:
            device_map = {"": 'cuda:%d' % device_id} if device_id >= 0 else {'': 'cuda'}

        # https://huggingface.co/blog/asr-chunking
        self.pipe = pipeline(
            "automatic-speech-recognition",
            model=self.lang_model,
            chunk_length_s=30,
            stride_length_s=5,
            batch_size=8,
            device_map=device_map,
        )
        if use_better:
            # even faster if not doing real time ASR
            # stride_length_s=5,  batch_size=8
            try:
                from optimum.bettertransformer import BetterTransformer
                self.pipe.model = BetterTransformer.transform(self.pipe.model, use_flash_attention_2=True)
            except Exception as e:
                print("No optimum, not using BetterTransformer: %s" % str(e), flush=True)

        if use_faster and have_use_faster and self.lang_model in ['openai/whisper-large-v2',
                                                                  'openai/whisper-large-v3']:
            self.pipe.model.to('cpu')
            del self.pipe.model
            clear_torch_cache()
            print("Using faster_whisper", flush=True)
            # has to come here, no framework and no config for model
            # pip install git+https://github.com/SYSTRAN/faster-whisper.git
            from faster_whisper import WhisperModel
            model_size = "large-v3" if self.lang_model == 'openai/whisper-large-v3' else "large-v2"
            # Run on GPU with FP16
            model = WhisperModel(model_size, device=self.device, compute_type="float16")
            # or run on GPU with INT8
            # model = WhisperModel(model_size, device="cuda", compute_type="int8_float16")
            # or run on CPU with INT8
            # model = WhisperModel(model_size, device="cpu", compute_type="int8")
            self.pipe.model = model

        if forced_decoder_ids is not None:
            try:
                self.pipe.model.config.forced_decoder_ids = forced_decoder_ids
            except Exception as exception_text:
                logger.info(
                    "Unable to set forced_decoder_ids parameter for whisper model"
                    f"Text of exception: {exception_text}"
                    "Therefore whisper model will use default mode for decoder"
                )

    def lazy_parse(self, blob: Blob) -> Iterator[Document]:
        """Lazily parse the blob."""

        import io

        try:
            from pydub import AudioSegment
        except ImportError:
            raise ImportError(
                "pydub package not found, please install it with `pip install pydub`"
            )

        try:
            import librosa
        except ImportError:
            raise ImportError(
                "librosa package not found, please install it with "
                "`pip install librosa`"
            )

        file = str(blob.path)
        if any([file.endswith(x) for x in ['.mp4', '.mpeg', '.mpg']]):
            import audioread.ffdec  # Use ffmpeg decoder
            aro = audioread.ffdec.FFmpegAudioFile(blob.path)
            y, sr = librosa.load(aro, sr=16000)
        else:

            # Audio file from disk
            audio = AudioSegment.from_file(blob.path)

            file_obj = io.BytesIO(audio.export(format="mp3").read())

            # Transcribe
            print(f"Transcribing part {blob.path}!")

            y, sr = librosa.load(file_obj, sr=16000)

        prediction = self.pipe(y.copy(), batch_size=8)["text"]

        yield Document(
            page_content=prediction,
            metadata={"source": blob.source},
        )


"""
Based upon ImageCaptionLoader in LangChain version: langchain/document_loaders/image_captions.py
But accepts preloaded model to avoid slowness in use and CUDA forking issues

Loader that loads image captions
By default, the loader utilizes the pre-trained BLIP image captioning model.
https://huggingface.co/Salesforce/blip-image-captioning-base

"""
from typing import List, Union, Any, Tuple

import requests
from langchain.docstore.document import Document
from langchain.document_loaders import ImageCaptionLoader

from utils import get_device, NullContext, clear_torch_cache, have_use_faster, makedirs

from importlib.metadata import distribution, PackageNotFoundError

try:
    assert distribution('bitsandbytes') is not None
    have_bitsandbytes = True
except (PackageNotFoundError, AssertionError):
    have_bitsandbytes = False


class H2OAudioCaptionLoader(ImageCaptionLoader):
    """Loader that loads the transcriptions of audio"""

    def __init__(self, path_audios: Union[str, List[str]] = None,
                 asr_model='openai/whisper-medium',
                 asr_gpu=True,
                 gpu_id='auto',
                 use_better=True,
                 use_faster=False,
                 ):
        super().__init__(path_audios)
        self.audio_paths = path_audios
        self.model = None
        self.asr_model = asr_model
        self.asr_gpu = asr_gpu
        self.context_class = NullContext
        self.gpu_id = gpu_id if isinstance(gpu_id, int) else 0
        self.device = 'cpu'
        self.device_map = {"": 'cpu'}
        self.set_context()
        self.use_better = use_better
        self.use_faster = use_faster
        self.files_out = []

    def set_context(self):
        if get_device() == 'cuda' and self.asr_gpu:
            import torch
            n_gpus = torch.cuda.device_count() if torch.cuda.is_available() else 0
            if n_gpus > 0:
                self.context_class = torch.device
                self.device = 'cuda'
            else:
                self.device = 'cpu'
        else:
            self.device = 'cpu'
        if get_device() == 'cuda' and self.asr_gpu:
            if self.gpu_id == 'auto':
                # blip2 has issues with multi-GPU.  Error says need to somehow set language model in device map
                # device_map = 'auto'
                self.gpu_id = 0
            self.device_map = {"": 'cuda:%d' % self.gpu_id}
        else:
            self.gpu_id = -1
            self.device_map = {"": 'cpu'}

    def load_model(self):
        try:
            import transformers
        except ImportError:
            raise ValueError(
                "`transformers` package not found, please install with "
                "`pip install transformers`."
            )
        self.set_context()
        if self.model:
            if str(self.model.pipe.model.device) != self.device_map['']:
                self.model.pipe.model.to(self.device_map[''])
            return self
        import torch
        with torch.no_grad():
            with self.context_class(self.device):
                context_class_cast = NullContext if self.device == 'cpu' else torch.autocast
                with context_class_cast(self.device):
                    self.model = OpenAIWhisperParserLocal(device=self.device,
                                                          device_id=self.gpu_id,
                                                          lang_model=self.asr_model,
                                                          use_better=self.use_better,
                                                          use_faster=self.use_faster,
                                                          )
        return self

    def set_audio_paths(self, path_audios: Union[str, List[str]]):
        """
        Load from a list of audio files
        """
        if isinstance(path_audios, str):
            self.audio_paths = [path_audios]
        else:
            self.audio_paths = path_audios

    def load(self, from_youtube=False) -> List[Document]:
        if self.model is None:
            self.load_model()

        # https://librosa.org/doc/main/generated/librosa.load.html
        if from_youtube:
            save_dir = tempfile.mkdtemp()
            makedirs(save_dir, exist_ok=True)
            youtube_loader = YoutubeAudioLoader(self.audio_paths, save_dir)
            loader = GenericLoader(youtube_loader, self.model)
            docs = loader.load()
            self.files_out = youtube_loader.files_out
            return docs
        else:
            docs = []
            for fil in self.audio_paths:
                loader = GenericLoader.from_filesystem(
                    os.path.dirname(fil),
                    glob=os.path.basename(fil),
                    parser=self.model)
                docs += loader.load()
            return docs

    def unload_model(self):
        if hasattr(self, 'model') and hasattr(self.model, 'pipe') and hasattr(self.model.pipe.model, 'cpu'):
            self.model.pipe.model.cpu()
            clear_torch_cache()


from typing import Iterable, List

from langchain.document_loaders.blob_loaders import FileSystemBlobLoader
from langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader


class YoutubeAudioLoader(BlobLoader):

    """Load YouTube urls as audio file(s)."""

    def __init__(self, urls: List[str], save_dir: str):
        if not isinstance(urls, list):
            raise TypeError("urls must be a list")

        self.urls = urls
        self.save_dir = save_dir
        self.files_out = []

    def yield_blobs(self) -> Iterable[Blob]:
        """Yield audio blobs for each url."""

        try:
            import yt_dlp
        except ImportError:
            raise ImportError(
                "yt_dlp package not found, please install it with "
                "`pip install yt_dlp`"
            )

        # Use yt_dlp to download audio given a YouTube url
        ydl_opts = {
            "format": "m4a/bestaudio/best",
            "noplaylist": True,
            "outtmpl": self.save_dir + "/%(title)s.%(ext)s",
            "postprocessors": [
                {
                    "key": "FFmpegExtractAudio",
                    "preferredcodec": "m4a",
                }
            ],
        }

        for url in self.urls:
            # Download file
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                ydl.download(url)

        # Yield the written blobs
        loader = FileSystemBlobLoader(self.save_dir, glob="*.m4a")
        self.files_out = [os.path.join(self.save_dir, f) for f in os.listdir(self.save_dir)]
        for blob in loader.yield_blobs():
            yield blob