Open-source speech recognition toolkit for training, inference, streaming ASR, VAD, punctuation, speaker diarization pipelines, and OpenAI-compatible/MCP serving.
Python asraudiochineseemotion-recognitionfunasrmcp-servermultilingual-asropenai-compatible-apiparaformerpunctuationpytorchreal-time-asrspeaker-diarizationspeech-recognitionspeech-to-textstreaming-asrtranscriptionvllmvoice-activity-detectionwhisper-alternative
Resolve merge conflict
游雁8912e0696af0
diff --cc funasr/datasets/audio_datasets/samplers.pyindex d34fdeae7,c8e7b0d71..9c87245ad--- a/funasr/datasets/audio_datasets/samplers.py+++ b/funasr/datasets/audio_datasets/samplers.py@@@ -2,71 -2,64 +2,71 @@@ import torcimport numpy as np+from funasr.register import tables+++[email protected]("batch_sampler_classes", "DynamicBatchLocalShuffleSampler")class BatchSampler(torch.utils.data.BatchSampler):- def __init__(self, dataset, batch_size_type: str="example", batch_size: int=100, sort_size: int=30, drop_last: bool=False, shuffle: bool=True, **kwargs):+ def __init__(self, dataset,- batch_type: str="example",- batch_size: int=100,- buffer_size: int=30,- drop_last: bool=False,- shuffle: bool=True,++ batch_type: str = "example",++ batch_size: int = 100,++ buffer_size: int = 30,++ drop_last: bool = False,++ shuffle: bool = True,+ **kwargs):self.drop_last = drop_lastself.pre_idx = -1self.dataset = datasetself.total_samples = len(dataset)- # self.batch_size_type = args.batch_size_type- # self.batch_size = args.batch_size- # self.sort_size = args.sort_size- # self.max_length_token = args.max_length_token- self.batch_size_type = batch_size_type+ self.batch_type = batch_typeself.batch_size = batch_size- self.sort_size = sort_size- self.max_length_token = kwargs.get("max_length_token", 5000)+ self.buffer_size = buffer_size+ self.max_token_length = kwargs.get("max_token_length", 5000)self.shuffle_idx = np.arange(self.total_samples)self.shuffle = shuffle--def __len__(self):return self.total_samples-++ def set_epoch(self, epoch):+ np.random.seed(epoch)-++def __iter__(self):- print("in sampler")if self.shuffle:np.random.shuffle(self.shuffle_idx)--++batch = []max_token = 0num_sample = 0--- iter_num = (self.total_samples-1) // self.buffer_size + 1- iter_num = (self.total_samples-1) // self.sort_size + 1- print("iter_num: ", iter_num)++++ iter_num = (self.total_samples - 1) // self.buffer_size + 1+ # print("iter_num: ", iter_num)for iter in range(self.pre_idx + 1, iter_num):datalen_with_index = []- for i in range(self.sort_size):- idx = iter * self.sort_size + i+ for i in range(self.buffer_size):+ idx = iter * self.buffer_size + iif idx >= self.total_samples:continue--++idx_map = self.shuffle_idx[idx]# prompt = self.dataset.indexed_dataset[idx_map]["prompt"]- sample_len_cur = self.dataset.indexed_dataset[idx_map]["source_len"] + \- self.dataset.indexed_dataset[idx_map]["target_len"]-+ sample_len_cur = self.dataset.get_source_len(idx_map) + \+ self.dataset.get_target_len(idx_map)-++datalen_with_index.append([idx, sample_len_cur])datalen_with_index_sort = sorted(datalen_with_index, key=lambda x: x[1])for item in datalen_with_index_sort:idx, sample_len_cur_raw = item- if sample_len_cur_raw > self.max_length_token:+ if sample_len_cur_raw > self.max_token_length:continue--++max_token_cur = max(max_token, sample_len_cur_raw)max_token_padding = 1 + num_sample- if self.batch_size_type == 'token':+ if self.batch_type == 'length':max_token_padding *= max_token_curif max_token_padding <= self.batch_size:batch.append(idx)@@@ -77,5 -70,5 +77,4 @@@batch = [idx]max_token = sample_len_cur_rawnum_sample = 1----++diff --cc funasr/metrics/compute_acc.pyindex 2b4583617,000000000..9d16e1f3bmode 100644,000000..100644--- a/funasr/metrics/compute_acc.py+++ b/funasr/metrics/compute_acc.py@@@ -1,23 -1,0 +1,23 @@@+import torch++def th_accuracy(pad_outputs, pad_targets, ignore_label):+ """Calculate accuracy.++ Args:+ pad_outputs (Tensor): Prediction tensors (B * Lmax, D).- pad_targets (LongTensor): Target label tensors (B, Lmax).++ pad_targets (LongTensor): Target label tensors (B, Lmax, D).+ ignore_label (int): Ignore label id.++ Returns:+ float: Accuracy value (0.0 - 1.0).++ """+ pad_pred = pad_outputs.view(+ pad_targets.size(0), pad_targets.size(1), pad_outputs.size(1)+ ).argmax(2)+ mask = pad_targets != ignore_label+ numerator = torch.sum(+ pad_pred.masked_select(mask) == pad_targets.masked_select(mask)+ )+ denominator = torch.sum(mask)+ return float(numerator) / float(denominator)diff --cc funasr/models/uniasr/e2e_uni_asr.pyindex 46c583293,14fb7f355..de7ed2944--- a/funasr/models/uniasr/e2e_uni_asr.py+++ b/funasr/models/uniasr/e2e_uni_asr.py@@@ -443,7 -443,6 +443,10 @@@ class UniASR(FunASRModel)# force_gatherable: to-device and to-tensor if scalar for DataParallelif self.length_normalized_loss:batch_size = int((text_lengths + 1).sum())++<<<<<<< HEAD:funasr/models/uniasr/e2e_uni_asr.py+++=======++>>>>>>> main:funasr/models/e2e_uni_asr.pyloss, stats, weight = force_gatherable((loss, stats, batch_size), loss.device)return loss, stats, weightdiff --cc funasr/schedulers/__init__.pyindex 2ee3a9ec7,e69de29bb..cba286aa3--- a/funasr/schedulers/__init__.py+++ b/funasr/schedulers/__init__.py@@@ -1,23 -1,0 +1,23 @@@+import torch+import torch.multiprocessing+import torch.nn+import torch.optim++from funasr.schedulers.noam_lr import NoamLR+from funasr.schedulers.tri_stage_scheduler import TriStageLR+from funasr.schedulers.warmup_lr import WarmupLR++scheduler_classes = dict(+ ReduceLROnPlateau=torch.optim.lr_scheduler.ReduceLROnPlateau,+ lambdalr=torch.optim.lr_scheduler.LambdaLR,+ steplr=torch.optim.lr_scheduler.StepLR,+ multisteplr=torch.optim.lr_scheduler.MultiStepLR,+ exponentiallr=torch.optim.lr_scheduler.ExponentialLR,+ CosineAnnealingLR=torch.optim.lr_scheduler.CosineAnnealingLR,+ noamlr=NoamLR,+ warmuplr=WarmupLR,+ tri_stage=TriStageLR,+ cycliclr=torch.optim.lr_scheduler.CyclicLR,+ onecyclelr=torch.optim.lr_scheduler.OneCycleLR,+ CosineAnnealingWarmRestarts=torch.optim.lr_scheduler.CosineAnnealingWarmRestarts,- )++)diff --cc funasr/tokenizer/abs_tokenizer.pyindex d43d7b2b7,fc2ccb3c3..548bf06af--- a/funasr/tokenizer/abs_tokenizer.py+++ b/funasr/tokenizer/abs_tokenizer.py@@@ -2,98 -2,13 +2,99 @@@ from abc import ABfrom abc import abstractmethodfrom typing import Iterablefrom typing import List+from pathlib import Path+from typing import Dict+from typing import Iterable+from typing import List+from typing import Union+import json++import numpy as np- class AbsTokenizer(ABC):- @abstractmethod- def text2tokens(self, line: str) -> List[str]:- raise NotImplementedError- @abstractmethod- def tokens2text(self, tokens: Iterable[str]) -> str:- raise NotImplementedError+ class AbsTokenizer(ABC):- @abstractmethod- def text2tokens(self, line: str) -> List[str]:- raise NotImplementedError++ @abstractmethod++ def text2tokens(self, line: str) -> List[str]:++ raise NotImplementedError++++ @abstractmethod++ def tokens2text(self, tokens: Iterable[str]) -> str:++ raise NotImplementedError+- @abstractmethod- def tokens2text(self, tokens: Iterable[str]) -> str:- raise NotImplementedError+class BaseTokenizer(ABC):- def __init__(self, token_list: Union[Path, str, Iterable[str]]=None,- unk_symbol: str = "<unk>",- **kwargs,- ):-- if token_list is not None:- if isinstance(token_list, (Path, str)) and token_list.endswith(".txt"):- token_list = Path(token_list)- self.token_list_repr = str(token_list)- self.token_list: List[str] = []-- with token_list.open("r", encoding="utf-8") as f:- for idx, line in enumerate(f):- line = line.rstrip()- self.token_list.append(line)- elif isinstance(token_list, (Path, str)) and token_list.endswith(".json"):- token_list = Path(token_list)- self.token_list_repr = str(token_list)- self.token_list: List[str] = []-- with open(token_list, 'r', encoding='utf-8') as f:- self.token_list = json.load(f)--- else:- self.token_list: List[str] = list(token_list)- self.token_list_repr = ""- for i, t in enumerate(self.token_list):- if i == 3:- break- self.token_list_repr += f"{t}, "- self.token_list_repr += f"... (NVocab={(len(self.token_list))})"-- self.token2id: Dict[str, int] = {}- for i, t in enumerate(self.token_list):- if t in self.token2id:- raise RuntimeError(f'Symbol "{t}" is duplicated')- self.token2id[t] = i-- self.unk_symbol = unk_symbol- if self.unk_symbol not in self.token2id:- raise RuntimeError(- f"Unknown symbol '{unk_symbol}' doesn't exist in the token_list"- )- self.unk_id = self.token2id[self.unk_symbol]-- def encode(self, text):- tokens = self.text2tokens(text)- text_ints = self.tokens2ids(tokens)-- return text_ints-- def decode(self, text_ints):- token = self.ids2tokens(text_ints)- text = self.tokens2text(token)- return text-- def get_num_vocabulary_size(self) -> int:- return len(self.token_list)-- def ids2tokens(self, integers: Union[np.ndarray, Iterable[int]]) -> List[str]:- if isinstance(integers, np.ndarray) and integers.ndim != 1:- raise ValueError(f"Must be 1 dim ndarray, but got {integers.ndim}")- return [self.token_list[i] for i in integers]-- def tokens2ids(self, tokens: Iterable[str]) -> List[int]:- return [self.token2id.get(i, self.unk_id) for i in tokens]-- @abstractmethod- def text2tokens(self, line: str) -> List[str]:- raise NotImplementedError-- @abstractmethod- def tokens2text(self, tokens: Iterable[str]) -> str:- raise NotImplementedError++ def __init__(self, token_list: Union[Path, str, Iterable[str]] = None,++ unk_symbol: str = "<unk>",++ **kwargs,++ ):++++ if token_list is not None:++ if isinstance(token_list, (Path, str)) and token_list.endswith(".txt"):++ token_list = Path(token_list)++ self.token_list_repr = str(token_list)++ self.token_list: List[str] = []++++ with token_list.open("r", encoding="utf-8") as f:++ for idx, line in enumerate(f):++ line = line.rstrip()++ self.token_list.append(line)++ elif isinstance(token_list, (Path, str)) and token_list.endswith(".json"):++ token_list = Path(token_list)++ self.token_list_repr = str(token_list)++ self.token_list: List[str] = []++++ with open(token_list, 'r', encoding='utf-8') as f:++ self.token_list = json.load(f)++++++ else:++ self.token_list: List[str] = list(token_list)++ self.token_list_repr = ""++ for i, t in enumerate(self.token_list):++ if i == 3:++ break++ self.token_list_repr += f"{t}, "++ self.token_list_repr += f"... (NVocab={(len(self.token_list))})"++++ self.token2id: Dict[str, int] = {}++ for i, t in enumerate(self.token_list):++ if t in self.token2id:++ raise RuntimeError(f'Symbol "{t}" is duplicated')++ self.token2id[t] = i++++ self.unk_symbol = unk_symbol++ if self.unk_symbol not in self.token2id:++ raise RuntimeError(++ f"Unknown symbol '{unk_symbol}' doesn't exist in the token_list"++ )++ self.unk_id = self.token2id[self.unk_symbol]++++ def encode(self, text):++ tokens = self.text2tokens(text)++ text_ints = self.tokens2ids(tokens)++++ return text_ints++++ def decode(self, text_ints):++ token = self.ids2tokens(text_ints)++ text = self.tokens2text(token)++ return text++++ def get_num_vocabulary_size(self) -> int:++ return len(self.token_list)++++ def ids2tokens(self, integers: Union[np.ndarray, Iterable[int]]) -> List[str]:++ if isinstance(integers, np.ndarray) and integers.ndim != 1:++ raise ValueError(f"Must be 1 dim ndarray, but got {integers.ndim}")++ return [self.token_list[i] for i in integers]++++ def tokens2ids(self, tokens: Iterable[str]) -> List[int]:++ return [self.token2id.get(i, self.unk_id) for i in tokens]++++ @abstractmethod++ def text2tokens(self, line: str) -> List[str]:++ raise NotImplementedError++++ @abstractmethod++ def tokens2text(self, tokens: Iterable[str]) -> str:++ raise NotImplementedErrordiff --cc funasr/tokenizer/char_tokenizer.pyindex 8c6c214f6,6c9a5a5b9..0635fd70c--- a/funasr/tokenizer/char_tokenizer.py+++ b/funasr/tokenizer/char_tokenizer.py@@@ -59,4 -57,4 +59,4 @@@ class CharTokenizer(BaseTokenizer)def tokens2text(self, tokens: Iterable[str]) -> str:tokens = [t if t != self.space_symbol else " " for t in tokens]-- return "".join(tokens)++ return "".join(tokens)