#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/dots3_note/modular_dots3_note.py.
#               Do NOT edit this file manually as any edits will be overwritten by the generation of
#             the file from the modular. If any change should be done, please apply the change to the
#                          modular_dots3_note.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 The Dots Studio team and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math

import numpy as np

from ...audio_utils import make_list_of_audio, mel_filter_bank
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, is_torch_available
from ...utils.import_utils import requires


if is_torch_available():
    import torch


@requires(backends=("torch",))
class Dots3NoteFeatureExtractor(SequenceFeatureExtractor):
    """Convert 16 kHz mono waveforms into Dots 3 Note Preview log-mel chunks."""

    model_input_names = ["input_features", "chunk_sample_lengths"]

    def __init__(
        self,
        feature_size: int = 128,
        sampling_rate: int = 16_000,
        padding_value: float = 0.0,
        n_fft: int = 400,
        hop_length: int = 160,
        chunk_length: int = 60,
        chunk_seconds: int | None = None,
        return_attention_mask: bool = False,
        dither: float = 0.0,
        **kwargs,
    ):
        super().__init__(
            feature_size=feature_size,
            sampling_rate=sampling_rate,
            padding_value=padding_value,
            return_attention_mask=return_attention_mask,
            **kwargs,
        )
        chunk_length = chunk_length if chunk_seconds is None else chunk_seconds
        self.n_fft = n_fft
        self.hop_length = hop_length
        self.chunk_length = chunk_length
        self.n_samples = chunk_length * sampling_rate
        self.nb_max_frames = self.n_samples // hop_length
        self.sampling_rate = sampling_rate
        self.dither = dither
        self.mel_filters = mel_filter_bank(
            num_frequency_bins=1 + n_fft // 2,
            num_mel_filters=feature_size,
            min_frequency=0.0,
            max_frequency=8000.0,
            sampling_rate=sampling_rate,
            norm="slaney",
            mel_scale="slaney",
        )

    def _torch_extract_fbank_features(self, waveform: np.ndarray, device: str = "cpu") -> np.ndarray:
        """
        Compute the log-mel spectrogram of the audio using PyTorch's GPU-accelerated STFT implementation with batching,
        yielding results similar to cpu computing with 1e-5 tolerance.
        """
        waveform = torch.from_numpy(waveform).to(device, torch.float32)
        window = torch.hann_window(self.n_fft, device=device)

        # Note: it would be better to dither the chunked waveform,
        # so overlapping signal does not get the same dithering.
        # But, chunking is happening inside pytorch, so it is here.
        if self.dither != 0.0:
            waveform += self.dither * torch.randn(waveform.shape, dtype=waveform.dtype, device=waveform.device)

        stft = torch.stft(waveform, self.n_fft, self.hop_length, window=window, return_complex=True)
        # `stft[..., :-1]` is a non-contiguous view; on some CPU backends the
        # downstream `mel_filters.T @ magnitudes` matmul hits a slow strided
        # path (observed ~8x slower). Forcing contiguity here is cheap and
        # keeps the matmul on the fast path.
        magnitudes = (stft[..., :-1].abs() ** 2).contiguous()

        mel_filters = torch.from_numpy(self.mel_filters).to(device, torch.float32)
        mel_spec = mel_filters.T @ magnitudes

        log_spec = torch.clamp(mel_spec, min=1e-10).log10()
        if waveform.dim() == 2:
            max_val = log_spec.max(dim=2, keepdim=True)[0].max(dim=1, keepdim=True)[0]
            log_spec = torch.maximum(log_spec, max_val - 8.0)
        else:
            log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
        log_spec = (log_spec + 4.0) / 4.0
        if device != "cpu":
            log_spec = log_spec.detach().cpu()
        return log_spec.numpy()

    def __call__(
        self,
        raw_speech,
        sampling_rate: int | None = None,
        return_tensors: str | TensorType | None = "pt",
        device: str = "cpu",
        **kwargs,
    ) -> BatchFeature:
        """Extract chunked log-mel features and their waveform sample lengths."""
        if sampling_rate is not None and sampling_rate != self.sampling_rate:
            raise ValueError(f"Expected sampling rate {self.sampling_rate}, got {sampling_rate}")
        chunks = []
        chunk_sample_lengths = []
        chunk_token_lengths = []
        audio_token_lengths = []

        for waveform in make_list_of_audio(raw_speech):
            waveform = torch.as_tensor(waveform, dtype=torch.float32)
            per_audio_tokens = 0
            for chunk in waveform.split(self.n_samples):
                sample_length = int(chunk.numel())
                # Three stride-2 convolutions downsample the mel frames by a factor of eight.
                token_length = math.ceil(sample_length / (self.hop_length * 8))
                chunks.append(chunk.cpu().numpy()[:, None])
                chunk_sample_lengths.append(sample_length)
                chunk_token_lengths.append(token_length)
                per_audio_tokens += token_length
            audio_token_lengths.append(per_audio_tokens)

        inputs = self.pad(
            BatchFeature({"input_features": chunks}),
            padding="max_length",
            max_length=self.n_samples,
            return_tensors="np",
            return_attention_mask=False,
        )
        input_features = self._torch_extract_fbank_features(inputs["input_features"].squeeze(-1), device)
        input_features = input_features[..., : max(chunk_token_lengths) * 8]
        data = {
            "input_features": torch.from_numpy(input_features).to(device),
            "chunk_sample_lengths": torch.tensor(chunk_sample_lengths, dtype=torch.long, device=device),
            "num_audio_tokens": torch.tensor(audio_token_lengths, dtype=torch.long, device=device),
        }
        return BatchFeature(data=data, tensor_type=return_tensors)


__all__ = ["Dots3NoteFeatureExtractor"]
