repo_id
stringlengths 18
103
| file_path
stringlengths 30
136
| content
stringlengths 2
3.36M
| __index_level_0__
int64 0
0
|
---|---|---|---|
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidjson | coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidjson/internal/biginteger.h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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.
#ifndef CEREAL_RAPIDJSON_BIGINTEGER_H_
#define CEREAL_RAPIDJSON_BIGINTEGER_H_
#include "../rapidjson.h"
#if defined(_MSC_VER) && !__INTEL_COMPILER && defined(_M_AMD64)
#include <intrin.h> // for _umul128
#pragma intrinsic(_umul128)
#endif
CEREAL_RAPIDJSON_NAMESPACE_BEGIN
namespace internal {
class BigInteger {
public:
typedef uint64_t Type;
BigInteger(const BigInteger& rhs) : count_(rhs.count_) {
std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
}
explicit BigInteger(uint64_t u) : count_(1) {
digits_[0] = u;
}
BigInteger(const char* decimals, size_t length) : count_(1) {
CEREAL_RAPIDJSON_ASSERT(length > 0);
digits_[0] = 0;
size_t i = 0;
const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19
while (length >= kMaxDigitPerIteration) {
AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration);
length -= kMaxDigitPerIteration;
i += kMaxDigitPerIteration;
}
if (length > 0)
AppendDecimal64(decimals + i, decimals + i + length);
}
BigInteger& operator=(const BigInteger &rhs)
{
if (this != &rhs) {
count_ = rhs.count_;
std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
}
return *this;
}
BigInteger& operator=(uint64_t u) {
digits_[0] = u;
count_ = 1;
return *this;
}
BigInteger& operator+=(uint64_t u) {
Type backup = digits_[0];
digits_[0] += u;
for (size_t i = 0; i < count_ - 1; i++) {
if (digits_[i] >= backup)
return *this; // no carry
backup = digits_[i + 1];
digits_[i + 1] += 1;
}
// Last carry
if (digits_[count_ - 1] < backup)
PushBack(1);
return *this;
}
BigInteger& operator*=(uint64_t u) {
if (u == 0) return *this = 0;
if (u == 1) return *this;
if (*this == 1) return *this = u;
uint64_t k = 0;
for (size_t i = 0; i < count_; i++) {
uint64_t hi;
digits_[i] = MulAdd64(digits_[i], u, k, &hi);
k = hi;
}
if (k > 0)
PushBack(k);
return *this;
}
BigInteger& operator*=(uint32_t u) {
if (u == 0) return *this = 0;
if (u == 1) return *this;
if (*this == 1) return *this = u;
uint64_t k = 0;
for (size_t i = 0; i < count_; i++) {
const uint64_t c = digits_[i] >> 32;
const uint64_t d = digits_[i] & 0xFFFFFFFF;
const uint64_t uc = u * c;
const uint64_t ud = u * d;
const uint64_t p0 = ud + k;
const uint64_t p1 = uc + (p0 >> 32);
digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32);
k = p1 >> 32;
}
if (k > 0)
PushBack(k);
return *this;
}
BigInteger& operator<<=(size_t shift) {
if (IsZero() || shift == 0) return *this;
size_t offset = shift / kTypeBit;
size_t interShift = shift % kTypeBit;
CEREAL_RAPIDJSON_ASSERT(count_ + offset <= kCapacity);
if (interShift == 0) {
std::memmove(digits_ + offset, digits_, count_ * sizeof(Type));
count_ += offset;
}
else {
digits_[count_] = 0;
for (size_t i = count_; i > 0; i--)
digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift));
digits_[offset] = digits_[0] << interShift;
count_ += offset;
if (digits_[count_])
count_++;
}
std::memset(digits_, 0, offset * sizeof(Type));
return *this;
}
bool operator==(const BigInteger& rhs) const {
return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0;
}
bool operator==(const Type rhs) const {
return count_ == 1 && digits_[0] == rhs;
}
BigInteger& MultiplyPow5(unsigned exp) {
static const uint32_t kPow5[12] = {
5,
5 * 5,
5 * 5 * 5,
5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
};
if (exp == 0) return *this;
for (; exp >= 27; exp -= 27) *this *= CEREAL_RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27
for (; exp >= 13; exp -= 13) *this *= static_cast<uint32_t>(1220703125u); // 5^13
if (exp > 0) *this *= kPow5[exp - 1];
return *this;
}
// Compute absolute difference of this and rhs.
// Assume this != rhs
bool Difference(const BigInteger& rhs, BigInteger* out) const {
int cmp = Compare(rhs);
CEREAL_RAPIDJSON_ASSERT(cmp != 0);
const BigInteger *a, *b; // Makes a > b
bool ret;
if (cmp < 0) { a = &rhs; b = this; ret = true; }
else { a = this; b = &rhs; ret = false; }
Type borrow = 0;
for (size_t i = 0; i < a->count_; i++) {
Type d = a->digits_[i] - borrow;
if (i < b->count_)
d -= b->digits_[i];
borrow = (d > a->digits_[i]) ? 1 : 0;
out->digits_[i] = d;
if (d != 0)
out->count_ = i + 1;
}
return ret;
}
int Compare(const BigInteger& rhs) const {
if (count_ != rhs.count_)
return count_ < rhs.count_ ? -1 : 1;
for (size_t i = count_; i-- > 0;)
if (digits_[i] != rhs.digits_[i])
return digits_[i] < rhs.digits_[i] ? -1 : 1;
return 0;
}
size_t GetCount() const { return count_; }
Type GetDigit(size_t index) const { CEREAL_RAPIDJSON_ASSERT(index < count_); return digits_[index]; }
bool IsZero() const { return count_ == 1 && digits_[0] == 0; }
private:
void AppendDecimal64(const char* begin, const char* end) {
uint64_t u = ParseUint64(begin, end);
if (IsZero())
*this = u;
else {
unsigned exp = static_cast<unsigned>(end - begin);
(MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u
}
}
void PushBack(Type digit) {
CEREAL_RAPIDJSON_ASSERT(count_ < kCapacity);
digits_[count_++] = digit;
}
static uint64_t ParseUint64(const char* begin, const char* end) {
uint64_t r = 0;
for (const char* p = begin; p != end; ++p) {
CEREAL_RAPIDJSON_ASSERT(*p >= '0' && *p <= '9');
r = r * 10u + static_cast<unsigned>(*p - '0');
}
return r;
}
// Assume a * b + k < 2^128
static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) {
#if defined(_MSC_VER) && defined(_M_AMD64)
uint64_t low = _umul128(a, b, outHigh) + k;
if (low < k)
(*outHigh)++;
return low;
#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__)
__extension__ typedef unsigned __int128 uint128;
uint128 p = static_cast<uint128>(a) * static_cast<uint128>(b);
p += k;
*outHigh = static_cast<uint64_t>(p >> 64);
return static_cast<uint64_t>(p);
#else
const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32;
uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1;
x1 += (x0 >> 32); // can't give carry
x1 += x2;
if (x1 < x2)
x3 += (static_cast<uint64_t>(1) << 32);
uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF);
uint64_t hi = x3 + (x1 >> 32);
lo += k;
if (lo < k)
hi++;
*outHigh = hi;
return lo;
#endif
}
static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000
static const size_t kCapacity = kBitCount / sizeof(Type);
static const size_t kTypeBit = sizeof(Type) * 8;
Type digits_[kCapacity];
size_t count_;
};
} // namespace internal
CEREAL_RAPIDJSON_NAMESPACE_END
#endif // CEREAL_RAPIDJSON_BIGINTEGER_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/script/equal.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_SCRIPT_EQUAL_H_
#define FST_SCRIPT_EQUAL_H_
#include <tuple>
#include <fst/equal.h>
#include <fst/script/arg-packs.h>
#include <fst/script/fst-class.h>
namespace fst {
namespace script {
using EqualInnerArgs = std::tuple<const FstClass &, const FstClass &, float>;
using EqualArgs = WithReturnValue<bool, EqualInnerArgs>;
template <class Arc>
void Equal(EqualArgs *args) {
const Fst<Arc> &fst1 = *(std::get<0>(args->args).GetFst<Arc>());
const Fst<Arc> &fst2 = *(std::get<1>(args->args).GetFst<Arc>());
args->retval = Equal(fst1, fst2, std::get<2>(args->args));
}
bool Equal(const FstClass &fst1, const FstClass &fst2, float delta = kDelta);
} // namespace script
} // namespace fst
#endif // FST_SCRIPT_EQUAL_H_
| 0 |
coqui_public_repos/inference-engine/third_party/cereal/include/cereal | coqui_public_repos/inference-engine/third_party/cereal/include/cereal/types/vector.hpp | /*! \file vector.hpp
\brief Support for types found in \<vector\>
\ingroup STLSupport */
/*
Copyright (c) 2014, Randolph Voorhies, Shane Grant
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CEREAL_TYPES_VECTOR_HPP_
#define CEREAL_TYPES_VECTOR_HPP_
#include "cereal/cereal.hpp"
#include <vector>
namespace cereal
{
//! Serialization for std::vectors of arithmetic (but not bool) using binary serialization, if supported
template <class Archive, class T, class A> inline
typename std::enable_if<traits::is_output_serializable<BinaryData<T>, Archive>::value
&& std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, void>::type
CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector<T, A> const & vector )
{
ar( make_size_tag( static_cast<size_type>(vector.size()) ) ); // number of elements
ar( binary_data( vector.data(), vector.size() * sizeof(T) ) );
}
//! Serialization for std::vectors of arithmetic (but not bool) using binary serialization, if supported
template <class Archive, class T, class A> inline
typename std::enable_if<traits::is_input_serializable<BinaryData<T>, Archive>::value
&& std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, void>::type
CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::vector<T, A> & vector )
{
size_type vectorSize;
ar( make_size_tag( vectorSize ) );
vector.resize( static_cast<std::size_t>( vectorSize ) );
ar( binary_data( vector.data(), static_cast<std::size_t>( vectorSize ) * sizeof(T) ) );
}
//! Serialization for non-arithmetic vector types
template <class Archive, class T, class A> inline
typename std::enable_if<(!traits::is_output_serializable<BinaryData<T>, Archive>::value
|| !std::is_arithmetic<T>::value) && !std::is_same<T, bool>::value, void>::type
CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector<T, A> const & vector )
{
ar( make_size_tag( static_cast<size_type>(vector.size()) ) ); // number of elements
for(auto && v : vector)
ar( v );
}
//! Serialization for non-arithmetic vector types
template <class Archive, class T, class A> inline
typename std::enable_if<(!traits::is_input_serializable<BinaryData<T>, Archive>::value
|| !std::is_arithmetic<T>::value) && !std::is_same<T, bool>::value, void>::type
CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::vector<T, A> & vector )
{
size_type size;
ar( make_size_tag( size ) );
vector.resize( static_cast<std::size_t>( size ) );
for(auto && v : vector)
ar( v );
}
//! Serialization for bool vector types
template <class Archive, class A> inline
void CEREAL_SAVE_FUNCTION_NAME( Archive & ar, std::vector<bool, A> const & vector )
{
ar( make_size_tag( static_cast<size_type>(vector.size()) ) ); // number of elements
for(const auto v : vector)
ar( static_cast<bool>(v) );
}
//! Serialization for bool vector types
template <class Archive, class A> inline
void CEREAL_LOAD_FUNCTION_NAME( Archive & ar, std::vector<bool, A> & vector )
{
size_type size;
ar( make_size_tag( size ) );
vector.resize( static_cast<std::size_t>( size ) );
for(auto v : vector)
{
bool b;
ar( b );
v = b;
}
}
} // namespace cereal
#endif // CEREAL_TYPES_VECTOR_HPP_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party | coqui_public_repos/STT/native_client/ctcdecode/third_party/ThreadPool/example.cpp | #include <iostream>
#include <vector>
#include <chrono>
#include "ThreadPool.h"
int main()
{
ThreadPool pool(4);
std::vector< std::future<int> > results;
for(int i = 0; i < 8; ++i) {
results.emplace_back(
pool.enqueue([i] {
std::cout << "hello " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "world " << i << std::endl;
return i*i;
})
);
}
for(auto && result: results)
std::cout << result.get() << ' ';
std::cout << std::endl;
return 0;
}
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/bin/fstprint.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/flags.h>
DEFINE_bool(acceptor, false, "Input in acceptor format?");
DEFINE_string(isymbols, "", "Input label symbol table");
DEFINE_string(osymbols, "", "Output label symbol table");
DEFINE_string(ssymbols, "", "State label symbol table");
DEFINE_bool(numeric, false, "Print numeric labels?");
DEFINE_string(save_isymbols, "", "Save input symbol table to file");
DEFINE_string(save_osymbols, "", "Save output symbol table to file");
DEFINE_bool(show_weight_one, false,
"Print/draw arc weights and final weights equal to semiring One?");
DEFINE_bool(allow_negative_labels, false,
"Allow negative labels (not recommended; may cause conflicts)?");
DEFINE_string(missing_symbol, "",
"Symbol to print when lookup fails (default raises error)");
int fstprint_main(int argc, char **argv);
int main(int argc, char **argv) { return fstprint_main(argc, argv); }
| 0 |
coqui_public_repos/TTS/TTS/vc | coqui_public_repos/TTS/TTS/vc/configs/shared_configs.py | from dataclasses import asdict, dataclass, field
from typing import Dict, List
from coqpit import Coqpit, check_argument
from TTS.config import BaseAudioConfig, BaseDatasetConfig, BaseTrainingConfig
@dataclass
class BaseVCConfig(BaseTrainingConfig):
"""Shared parameters among all the tts models.
Args:
audio (BaseAudioConfig):
Audio processor config object instance.
batch_group_size (int):
Size of the batch groups used for bucketing. By default, the dataloader orders samples by the sequence
length for a more efficient and stable training. If `batch_group_size > 1` then it performs bucketing to
prevent using the same batches for each epoch.
loss_masking (bool):
enable / disable masking loss values against padded segments of samples in a batch.
min_text_len (int):
Minimum length of input text to be used. All shorter samples will be ignored. Defaults to 0.
max_text_len (int):
Maximum length of input text to be used. All longer samples will be ignored. Defaults to float("inf").
min_audio_len (int):
Minimum length of input audio to be used. All shorter samples will be ignored. Defaults to 0.
max_audio_len (int):
Maximum length of input audio to be used. All longer samples will be ignored. The maximum length in the
dataset defines the VRAM used in the training. Hence, pay attention to this value if you encounter an
OOM error in training. Defaults to float("inf").
compute_f0 (int):
(Not in use yet).
compute_energy (int):
(Not in use yet).
compute_linear_spec (bool):
If True data loader computes and returns linear spectrograms alongside the other data.
precompute_num_workers (int):
Number of workers to precompute features. Defaults to 0.
use_noise_augment (bool):
Augment the input audio with random noise.
start_by_longest (bool):
If True, the data loader will start loading the longest batch first. It is useful for checking OOM issues.
Defaults to False.
shuffle (bool):
If True, the data loader will shuffle the dataset when there is not sampler defined. Defaults to True.
drop_last (bool):
If True, the data loader will drop the last batch if it is not complete. It helps to prevent
issues that emerge from the partial batch statistics. Defaults to True.
add_blank (bool):
Add blank characters between each other two characters. It improves performance for some models at expense
of slower run-time due to the longer input sequence.
datasets (List[BaseDatasetConfig]):
List of datasets used for training. If multiple datasets are provided, they are merged and used together
for training.
optimizer (str):
Optimizer used for the training. Set one from `torch.optim.Optimizer` or `TTS.utils.training`.
Defaults to ``.
optimizer_params (dict):
Optimizer kwargs. Defaults to `{"betas": [0.8, 0.99], "weight_decay": 0.0}`
lr_scheduler (str):
Learning rate scheduler for the training. Use one from `torch.optim.Scheduler` schedulers or
`TTS.utils.training`. Defaults to ``.
lr_scheduler_params (dict):
Parameters for the generator learning rate scheduler. Defaults to `{"warmup": 4000}`.
test_sentences (List[str]):
List of sentences to be used at testing. Defaults to '[]'
eval_split_max_size (int):
Number maximum of samples to be used for evaluation in proportion split. Defaults to None (Disabled).
eval_split_size (float):
If between 0.0 and 1.0 represents the proportion of the dataset to include in the evaluation set.
If > 1, represents the absolute number of evaluation samples. Defaults to 0.01 (1%).
use_speaker_weighted_sampler (bool):
Enable / Disable the batch balancer by speaker. Defaults to ```False```.
speaker_weighted_sampler_alpha (float):
Number that control the influence of the speaker sampler weights. Defaults to ```1.0```.
use_language_weighted_sampler (bool):
Enable / Disable the batch balancer by language. Defaults to ```False```.
language_weighted_sampler_alpha (float):
Number that control the influence of the language sampler weights. Defaults to ```1.0```.
use_length_weighted_sampler (bool):
Enable / Disable the batch balancer by audio length. If enabled the dataset will be divided
into 10 buckets considering the min and max audio of the dataset. The sampler weights will be
computed forcing to have the same quantity of data for each bucket in each training batch. Defaults to ```False```.
length_weighted_sampler_alpha (float):
Number that control the influence of the length sampler weights. Defaults to ```1.0```.
"""
audio: BaseAudioConfig = field(default_factory=BaseAudioConfig)
# training params
batch_group_size: int = 0
loss_masking: bool = None
# dataloading
min_audio_len: int = 1
max_audio_len: int = float("inf")
min_text_len: int = 1
max_text_len: int = float("inf")
compute_f0: bool = False
compute_energy: bool = False
compute_linear_spec: bool = False
precompute_num_workers: int = 0
use_noise_augment: bool = False
start_by_longest: bool = False
shuffle: bool = False
drop_last: bool = False
# dataset
datasets: List[BaseDatasetConfig] = field(default_factory=lambda: [BaseDatasetConfig()])
# optimizer
optimizer: str = "radam"
optimizer_params: dict = None
# scheduler
lr_scheduler: str = None
lr_scheduler_params: dict = field(default_factory=lambda: {})
# testing
test_sentences: List[str] = field(default_factory=lambda: [])
# evaluation
eval_split_max_size: int = None
eval_split_size: float = 0.01
# weighted samplers
use_speaker_weighted_sampler: bool = False
speaker_weighted_sampler_alpha: float = 1.0
use_language_weighted_sampler: bool = False
language_weighted_sampler_alpha: float = 1.0
use_length_weighted_sampler: bool = False
length_weighted_sampler_alpha: float = 1.0
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/script/topsort.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/script/fst-class.h>
#include <fst/script/script-impl.h>
#include <fst/script/topsort.h>
namespace fst {
namespace script {
bool TopSort(MutableFstClass *fst) {
TopSortArgs args(fst);
Apply<Operation<TopSortArgs>>("TopSort", fst->ArcType(), &args);
return args.retval;
}
REGISTER_FST_OPERATION(TopSort, StdArc, TopSortArgs);
REGISTER_FST_OPERATION(TopSort, LogArc, TopSortArgs);
REGISTER_FST_OPERATION(TopSort, Log64Arc, TopSortArgs);
} // namespace script
} // namespace fst
| 0 |
coqui_public_repos/inference-engine/third_party | coqui_public_repos/inference-engine/third_party/tensorflow/mfcc_dct.cc | /* Copyright 2017 The TensorFlow Authors. 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.
==============================================================================*/
#include "mfcc_dct.h"
#include <cmath>
namespace tensorflow {
MfccDct::MfccDct() : initialized_(false) {}
bool MfccDct::Initialize(int input_length, int coefficient_count) {
coefficient_count_ = coefficient_count;
input_length_ = input_length;
if (coefficient_count_ < 1) {
// LOG(ERROR) << "Coefficient count must be positive.";
return false;
}
if (input_length < 1) {
// LOG(ERROR) << "Input length must be positive.";
return false;
}
if (coefficient_count_ > input_length_) {
// LOG(ERROR) << "Coefficient count must be less than or equal to "
// << "input length.";
return false;
}
cosines_.resize(coefficient_count_);
double fnorm = sqrt(2.0 / input_length_);
// Some platforms don't have M_PI, so define a local constant here.
const double pi = std::atan(1) * 4;
double arg = pi / input_length_;
for (int i = 0; i < coefficient_count_; ++i) {
cosines_[i].resize(input_length_);
for (int j = 0; j < input_length_; ++j) {
cosines_[i][j] = fnorm * cos(i * arg * (j + 0.5));
}
}
initialized_ = true;
return true;
}
void MfccDct::Compute(const std::vector<double> &input,
std::vector<double> *output) const {
if (!initialized_) {
// LOG(ERROR) << "DCT not initialized.";
return;
}
output->resize(coefficient_count_);
int length = input.size();
if (length > input_length_) {
length = input_length_;
}
for (int i = 0; i < coefficient_count_; ++i) {
double sum = 0.0;
for (int j = 0; j < length; ++j) {
sum += cosines_[i][j] * input[j];
}
(*output)[i] = sum;
}
}
} // namespace tensorflow
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/script/relabel.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_SCRIPT_RELABEL_H_
#define FST_SCRIPT_RELABEL_H_
#include <algorithm>
#include <tuple>
#include <utility>
#include <vector>
#include <fst/relabel.h>
#include <fst/script/fst-class.h>
namespace fst {
namespace script {
using RelabelArgs1 = std::tuple<MutableFstClass *, const SymbolTable *,
const SymbolTable *, const string &, bool,
const SymbolTable *, const SymbolTable *,
const string &, bool>;
template <class Arc>
void Relabel(RelabelArgs1 *args) {
MutableFst<Arc> *ofst = std::get<0>(*args)->GetMutableFst<Arc>();
Relabel(ofst, std::get<1>(*args), std::get<2>(*args), std::get<3>(*args),
std::get<4>(*args), std::get<5>(*args), std::get<6>(*args),
std::get<7>(*args), std::get<8>(*args));
}
using LabelPair = std::pair<int64, int64>;
using RelabelArgs2 = std::tuple<MutableFstClass *,
const std::vector<LabelPair> &,
const std::vector<LabelPair> &>;
template <class Arc>
void Relabel(RelabelArgs2 *args) {
MutableFst<Arc> *ofst = std::get<0>(*args)->GetMutableFst<Arc>();
using LabelPair = std::pair<typename Arc::Label, typename Arc::Label>;
// In case the MutableFstClass::Label is not the same as Arc::Label,
// make a copy.
std::vector<LabelPair> typed_ipairs(std::get<1>(*args).size());
std::copy(std::get<1>(*args).begin(), std::get<1>(*args).end(),
typed_ipairs.begin());
std::vector<LabelPair> typed_opairs(std::get<2>(*args).size());
std::copy(std::get<2>(*args).begin(), std::get<2>(*args).end(),
typed_opairs.begin());
Relabel(ofst, typed_ipairs, typed_opairs);
}
void Relabel(MutableFstClass *ofst,
const SymbolTable *old_isymbols, const SymbolTable *new_isymbols,
const string &unknown_isymbol, bool attach_new_isymbols,
const SymbolTable *old_osymbols, const SymbolTable *new_osymbols,
const string &unknown_osymbol, bool attach_new_osymbols);
void Relabel(MutableFstClass *ofst, const std::vector<LabelPair> &ipairs,
const std::vector<LabelPair> &opairs);
} // namespace script
} // namespace fst
#endif // FST_SCRIPT_RELABEL_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/script/compile.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <istream>
#include <string>
#include <fst/script/compile.h>
#include <fst/script/fst-class.h>
#include <fst/script/script-impl.h>
namespace fst {
namespace script {
void CompileFst(std::istream &istrm, const string &source, const string &dest,
const string &fst_type, const string &arc_type,
const SymbolTable *isyms, const SymbolTable *osyms,
const SymbolTable *ssyms, bool accep, bool ikeep, bool okeep,
bool nkeep, bool allow_negative_labels) {
std::unique_ptr<FstClass> fst(
CompileFstInternal(istrm, source, fst_type, arc_type, isyms, osyms, ssyms,
accep, ikeep, okeep, nkeep, allow_negative_labels));
fst->Write(dest);
}
FstClass *CompileFstInternal(std::istream &istrm, const string &source,
const string &fst_type, const string &arc_type,
const SymbolTable *isyms, const SymbolTable *osyms,
const SymbolTable *ssyms, bool accep, bool ikeep,
bool okeep, bool nkeep,
bool allow_negative_labels) {
CompileFstInnerArgs iargs(istrm, source, fst_type, isyms, osyms, ssyms, accep,
ikeep, okeep, nkeep, allow_negative_labels);
CompileFstArgs args(iargs);
Apply<Operation<CompileFstArgs>>("CompileFstInternal", arc_type, &args);
return args.retval;
}
// This registers 2; 1 does not require registration.
REGISTER_FST_OPERATION(CompileFstInternal, StdArc, CompileFstArgs);
REGISTER_FST_OPERATION(CompileFstInternal, LogArc, CompileFstArgs);
REGISTER_FST_OPERATION(CompileFstInternal, Log64Arc, CompileFstArgs);
} // namespace script
} // namespace fst
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/pair-weight.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Pair weight templated base class for weight classes that contain two weights
// (e.g. Product, Lexicographic).
#ifndef FST_PAIR_WEIGHT_H_
#define FST_PAIR_WEIGHT_H_
#include <climits>
#include <stack>
#include <string>
#include <utility>
#include <fst/flags.h>
#include <fst/log.h>
#include <fst/weight.h>
namespace fst {
template <class W1, class W2>
class PairWeight {
public:
using ReverseWeight =
PairWeight<typename W1::ReverseWeight, typename W2::ReverseWeight>;
PairWeight() {}
PairWeight(const PairWeight &weight)
: value1_(weight.value1_), value2_(weight.value2_) {}
PairWeight(W1 w1, W2 w2) : value1_(std::move(w1)), value2_(std::move(w2)) {}
static const PairWeight<W1, W2> &Zero() {
static const PairWeight zero(W1::Zero(), W2::Zero());
return zero;
}
static const PairWeight<W1, W2> &One() {
static const PairWeight one(W1::One(), W2::One());
return one;
}
static const PairWeight<W1, W2> &NoWeight() {
static const PairWeight no_weight(W1::NoWeight(), W2::NoWeight());
return no_weight;
}
std::istream &Read(std::istream &strm) {
value1_.Read(strm);
return value2_.Read(strm);
}
std::ostream &Write(std::ostream &strm) const {
value1_.Write(strm);
return value2_.Write(strm);
}
PairWeight<W1, W2> &operator=(const PairWeight<W1, W2> &weight) {
value1_ = weight.Value1();
value2_ = weight.Value2();
return *this;
}
bool Member() const { return value1_.Member() && value2_.Member(); }
size_t Hash() const {
const auto h1 = value1_.Hash();
const auto h2 = value2_.Hash();
static constexpr int lshift = 5;
static constexpr int rshift = CHAR_BIT * sizeof(size_t) - 5;
return h1 << lshift ^ h1 >> rshift ^ h2;
}
PairWeight<W1, W2> Quantize(float delta = kDelta) const {
return PairWeight<W1, W2>(value1_.Quantize(delta), value2_.Quantize(delta));
}
ReverseWeight Reverse() const {
return ReverseWeight(value1_.Reverse(), value2_.Reverse());
}
const W1 &Value1() const { return value1_; }
const W2 &Value2() const { return value2_; }
void SetValue1(const W1 &weight) { value1_ = weight; }
void SetValue2(const W2 &weight) { value2_ = weight; }
private:
W1 value1_;
W2 value2_;
};
template <class W1, class W2>
inline bool operator==(const PairWeight<W1, W2> &w1,
const PairWeight<W1, W2> &w2) {
return w1.Value1() == w2.Value1() && w1.Value2() == w2.Value2();
}
template <class W1, class W2>
inline bool operator!=(const PairWeight<W1, W2> &w1,
const PairWeight<W1, W2> &w2) {
return w1.Value1() != w2.Value1() || w1.Value2() != w2.Value2();
}
template <class W1, class W2>
inline bool ApproxEqual(const PairWeight<W1, W2> &w1,
const PairWeight<W1, W2> &w2, float delta = kDelta) {
return ApproxEqual(w1.Value1(), w2.Value1(), delta) &&
ApproxEqual(w1.Value2(), w2.Value2(), delta);
}
template <class W1, class W2>
inline std::ostream &operator<<(std::ostream &strm,
const PairWeight<W1, W2> &weight) {
CompositeWeightWriter writer(strm);
writer.WriteBegin();
writer.WriteElement(weight.Value1());
writer.WriteElement(weight.Value2());
writer.WriteEnd();
return strm;
}
template <class W1, class W2>
inline std::istream &operator>>(std::istream &strm,
PairWeight<W1, W2> &weight) {
CompositeWeightReader reader(strm);
reader.ReadBegin();
W1 w1;
reader.ReadElement(&w1);
weight.SetValue1(w1);
W2 w2;
reader.ReadElement(&w2, true);
weight.SetValue2(w2);
reader.ReadEnd();
return strm;
}
// This function object returns weights by calling the underlying generators
// and forming a pair. This is intended primarily for testing.
template <class W1, class W2>
class WeightGenerate<PairWeight<W1, W2>> {
public:
using Weight = PairWeight<W1, W2>;
using Generate1 = WeightGenerate<W1>;
using Generate2 = WeightGenerate<W2>;
explicit WeightGenerate(bool allow_zero = true)
: generate1_(allow_zero), generate2_(allow_zero) {}
Weight operator()() const { return Weight(generate1_(), generate2_()); }
private:
Generate1 generate1_;
Generate2 generate2_;
};
} // namespace fst
#endif // FST_PAIR_WEIGHT_H_
| 0 |
coqui_public_repos/TTS/TTS/vocoder | coqui_public_repos/TTS/TTS/vocoder/layers/parallel_wavegan.py | import torch
from torch.nn import functional as F
class ResidualBlock(torch.nn.Module):
"""Residual block module in WaveNet."""
def __init__(
self,
kernel_size=3,
res_channels=64,
gate_channels=128,
skip_channels=64,
aux_channels=80,
dropout=0.0,
dilation=1,
bias=True,
use_causal_conv=False,
):
super().__init__()
self.dropout = dropout
# no future time stamps available
if use_causal_conv:
padding = (kernel_size - 1) * dilation
else:
assert (kernel_size - 1) % 2 == 0, "Not support even number kernel size."
padding = (kernel_size - 1) // 2 * dilation
self.use_causal_conv = use_causal_conv
# dilation conv
self.conv = torch.nn.Conv1d(
res_channels, gate_channels, kernel_size, padding=padding, dilation=dilation, bias=bias
)
# local conditioning
if aux_channels > 0:
self.conv1x1_aux = torch.nn.Conv1d(aux_channels, gate_channels, 1, bias=False)
else:
self.conv1x1_aux = None
# conv output is split into two groups
gate_out_channels = gate_channels // 2
self.conv1x1_out = torch.nn.Conv1d(gate_out_channels, res_channels, 1, bias=bias)
self.conv1x1_skip = torch.nn.Conv1d(gate_out_channels, skip_channels, 1, bias=bias)
def forward(self, x, c):
"""
x: B x D_res x T
c: B x D_aux x T
"""
residual = x
x = F.dropout(x, p=self.dropout, training=self.training)
x = self.conv(x)
# remove future time steps if use_causal_conv conv
x = x[:, :, : residual.size(-1)] if self.use_causal_conv else x
# split into two part for gated activation
splitdim = 1
xa, xb = x.split(x.size(splitdim) // 2, dim=splitdim)
# local conditioning
if c is not None:
assert self.conv1x1_aux is not None
c = self.conv1x1_aux(c)
ca, cb = c.split(c.size(splitdim) // 2, dim=splitdim)
xa, xb = xa + ca, xb + cb
x = torch.tanh(xa) * torch.sigmoid(xb)
# for skip connection
s = self.conv1x1_skip(x)
# for residual connection
x = (self.conv1x1_out(x) + residual) * (0.5**2)
return x, s
| 0 |
coqui_public_repos/inference-engine/third_party | coqui_public_repos/inference-engine/third_party/tensorflow/integral_types.h | /* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_
#define TENSORFLOW_CORE_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_
// IWYU pragma: private, include "third_party/tensorflow/core/platform/types.h"
// IWYU pragma: friend third_party/tensorflow/core/platform/types.h
namespace tensorflow {
typedef signed char int8;
typedef short int16;
typedef int int32;
typedef long long int64;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PLATFORM_DEFAULT_INTEGRAL_TYPES_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/script/push.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_SCRIPT_PUSH_H_
#define FST_SCRIPT_PUSH_H_
#include <tuple>
#include <fst/push.h>
#include <fst/script/fst-class.h>
namespace fst {
namespace script {
using PushArgs1 = std::tuple<MutableFstClass *, ReweightType, float, bool>;
template <class Arc>
void Push(PushArgs1 *args) {
MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>();
Push(fst, std::get<1>(*args), std::get<2>(*args), std::get<3>(*args));
}
using PushArgs2 = std::tuple<const FstClass &, MutableFstClass *, uint32,
ReweightType, float>;
template <class Arc>
void Push(PushArgs2 *args) {
const Fst<Arc> &ifst = *(std::get<0>(*args).GetFst<Arc>());
MutableFst<Arc> *ofst = std::get<1>(*args)->GetMutableFst<Arc>();
switch (std::get<3>(*args)) {
case REWEIGHT_TO_FINAL: {
Push<Arc, REWEIGHT_TO_FINAL>(ifst, ofst, std::get<2>(*args),
std::get<4>(*args));
return;
}
case REWEIGHT_TO_INITIAL: {
Push<Arc, REWEIGHT_TO_INITIAL>(ifst, ofst, std::get<2>(*args),
std::get<4>(*args));
return;
}
}
}
void Push(MutableFstClass *fst, ReweightType rew_type, float delta = kDelta,
bool remove_total_weight = false);
void Push(const FstClass &ifst, MutableFstClass *ofst, uint32 flags,
ReweightType rew_type, float delta = kDelta);
} // namespace script
} // namespace fst
#endif // FST_SCRIPT_PUSH_H_
| 0 |
coqui_public_repos/TTS/TTS/tts/utils/text | coqui_public_repos/TTS/TTS/tts/utils/text/french/abbreviations.py | import re
# List of (regular expression, replacement) pairs for abbreviations in french:
abbreviations_fr = [
(re.compile("\\b%s\\." % x[0], re.IGNORECASE), x[1])
for x in [
("M", "monsieur"),
("Mlle", "mademoiselle"),
("Mlles", "mesdemoiselles"),
("Mme", "Madame"),
("Mmes", "Mesdames"),
("N.B", "nota bene"),
("M", "monsieur"),
("p.c.q", "parce que"),
("Pr", "professeur"),
("qqch", "quelque chose"),
("rdv", "rendez-vous"),
("max", "maximum"),
("min", "minimum"),
("no", "numéro"),
("adr", "adresse"),
("dr", "docteur"),
("st", "saint"),
("co", "companie"),
("jr", "junior"),
("sgt", "sergent"),
("capt", "capitain"),
("col", "colonel"),
("av", "avenue"),
("av. J.-C", "avant Jésus-Christ"),
("apr. J.-C", "après Jésus-Christ"),
("art", "article"),
("boul", "boulevard"),
("c.-à-d", "c’est-à-dire"),
("etc", "et cetera"),
("ex", "exemple"),
("excl", "exclusivement"),
("boul", "boulevard"),
]
] + [
(re.compile("\\b%s" % x[0]), x[1])
for x in [
("Mlle", "mademoiselle"),
("Mlles", "mesdemoiselles"),
("Mme", "Madame"),
("Mmes", "Mesdames"),
]
]
| 0 |
coqui_public_repos/STT-examples/android_mic_streaming/app/src/main/res | coqui_public_repos/STT-examples/android_mic_streaming/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml | <?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon> | 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/bi-table.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Classes for representing a bijective mapping between an arbitrary entry
// of type T and a signed integral ID.
#ifndef FST_BI_TABLE_H_
#define FST_BI_TABLE_H_
#include <deque>
#include <memory>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <fst/log.h>
#include <fst/memory.h>
namespace fst {
// Bitables model bijective mappings between entries of an arbitrary type T and
// an signed integral ID of type I. The IDs are allocated starting from 0 in
// order.
//
// template <class I, class T>
// class BiTable {
// public:
//
// // Required constructors.
// BiTable();
//
// // Looks up integer ID from entry. If it doesn't exist and insert
// / is true, adds it; otherwise, returns -1.
// I FindId(const T &entry, bool insert = true);
//
// // Looks up entry from integer ID.
// const T &FindEntry(I) const;
//
// // Returns number of stored entries.
// I Size() const;
// };
// An implementation using a hash map for the entry to ID mapping. H is the
// hash function and E is the equality function. If passed to the constructor,
// ownership is given to this class.
template <class I, class T, class H, class E = std::equal_to<T>>
class HashBiTable {
public:
// Reserves space for table_size elements. If passing H and E to the
// constructor, this class owns them.
explicit HashBiTable(size_t table_size = 0, H *h = nullptr, E *e = nullptr) :
hash_func_(h ? h : new H()), hash_equal_(e ? e : new E()),
entry2id_(table_size, *hash_func_, *hash_equal_) {
if (table_size) id2entry_.reserve(table_size);
}
HashBiTable(const HashBiTable<I, T, H, E> &table)
: hash_func_(new H(*table.hash_func_)),
hash_equal_(new E(*table.hash_equal_)),
entry2id_(table.entry2id_.begin(), table.entry2id_.end(),
table.entry2id_.size(), *hash_func_, *hash_equal_),
id2entry_(table.id2entry_) {}
I FindId(const T &entry, bool insert = true) {
if (!insert) {
const auto it = entry2id_.find(entry);
return it == entry2id_.end() ? -1 : it->second - 1;
}
I &id_ref = entry2id_[entry];
if (id_ref == 0) { // T not found; stores and assigns a new ID.
id2entry_.push_back(entry);
id_ref = id2entry_.size();
}
return id_ref - 1; // NB: id_ref = ID + 1.
}
const T &FindEntry(I s) const { return id2entry_[s]; }
I Size() const { return id2entry_.size(); }
// TODO(riley): Add fancy clear-to-size, as in CompactHashBiTable.
void Clear() {
entry2id_.clear();
id2entry_.clear();
}
private:
std::unique_ptr<H> hash_func_;
std::unique_ptr<E> hash_equal_;
std::unordered_map<T, I, H, E> entry2id_;
std::vector<T> id2entry_;
};
// Enables alternative hash set representations below.
enum HSType { HS_STL = 0, HS_DENSE = 1, HS_SPARSE = 2, HS_FLAT = 3 };
// Default hash set is STL hash_set.
template <class K, class H, class E, HSType HS>
struct HashSet : public std::unordered_set<K, H, E, PoolAllocator<K>> {
explicit HashSet(size_t n = 0, const H &h = H(), const E &e = E())
: std::unordered_set<K, H, E, PoolAllocator<K>>(n, h, e) {}
void rehash(size_t n) {}
};
// An implementation using a hash set for the entry to ID mapping. The hash set
// holds keys which are either the ID or kCurrentKey. These keys can be mapped
// to entries either by looking up in the entry vector or, if kCurrentKey, in
// current_entry_. The hash and key equality functions map to entries first. H
// is the hash function and E is the equality function. If passed to the
// constructor, ownership is given to this class.
template <class I, class T, class H, class E = std::equal_to<T>,
HSType HS = HS_FLAT>
class CompactHashBiTable {
public:
friend class HashFunc;
friend class HashEqual;
// Reserves space for table_size elements. If passing H and E to the
// constructor, this class owns them.
explicit CompactHashBiTable(size_t table_size = 0, H *h = nullptr,
E *e = nullptr) :
hash_func_(h ? h : new H()), hash_equal_(e ? e : new E()),
compact_hash_func_(*this), compact_hash_equal_(*this),
keys_(table_size, compact_hash_func_, compact_hash_equal_) {
if (table_size) id2entry_.reserve(table_size);
}
CompactHashBiTable(const CompactHashBiTable<I, T, H, E, HS> &table)
: hash_func_(new H(*table.hash_func_)),
hash_equal_(new E(*table.hash_equal_)),
compact_hash_func_(*this), compact_hash_equal_(*this),
keys_(table.keys_.size(), compact_hash_func_, compact_hash_equal_),
id2entry_(table.id2entry_) {
keys_.insert(table.keys_.begin(), table.keys_.end());
}
I FindId(const T &entry, bool insert = true) {
current_entry_ = &entry;
if (insert) {
auto result = keys_.insert(kCurrentKey);
if (!result.second) return *result.first; // Already exists.
// Overwrites kCurrentKey with a new key value; this is safe because it
// doesn't affect hashing or equality testing.
I key = id2entry_.size();
const_cast<I &>(*result.first) = key;
id2entry_.push_back(entry);
return key;
}
const auto it = keys_.find(kCurrentKey);
return it == keys_.end() ? -1 : *it;
}
const T &FindEntry(I s) const { return id2entry_[s]; }
I Size() const { return id2entry_.size(); }
// Clears content; with argument, erases last n IDs.
void Clear(ssize_t n = -1) {
if (n < 0 || n >= id2entry_.size()) { // Clears completely.
keys_.clear();
id2entry_.clear();
} else if (n == id2entry_.size() - 1) { // Leaves only key 0.
const T entry = FindEntry(0);
keys_.clear();
id2entry_.clear();
FindId(entry, true);
} else {
while (n-- > 0) {
I key = id2entry_.size() - 1;
keys_.erase(key);
id2entry_.pop_back();
}
keys_.rehash(0);
}
}
private:
static constexpr I kCurrentKey = -1;
static constexpr I kEmptyKey = -2;
static constexpr I kDeletedKey = -3;
class HashFunc {
public:
explicit HashFunc(const CompactHashBiTable &ht) : ht_(&ht) {}
size_t operator()(I k) const {
if (k >= kCurrentKey) {
return (*ht_->hash_func_)(ht_->Key2Entry(k));
} else {
return 0;
}
}
private:
const CompactHashBiTable *ht_;
};
class HashEqual {
public:
explicit HashEqual(const CompactHashBiTable &ht) : ht_(&ht) {}
bool operator()(I k1, I k2) const {
if (k1 == k2) {
return true;
} else if (k1 >= kCurrentKey && k2 >= kCurrentKey) {
return (*ht_->hash_equal_)(ht_->Key2Entry(k1), ht_->Key2Entry(k2));
} else {
return false;
}
}
private:
const CompactHashBiTable *ht_;
};
using KeyHashSet = HashSet<I, HashFunc, HashEqual, HS>;
const T &Key2Entry(I k) const {
if (k == kCurrentKey) {
return *current_entry_;
} else {
return id2entry_[k];
}
}
std::unique_ptr<H> hash_func_;
std::unique_ptr<E> hash_equal_;
HashFunc compact_hash_func_;
HashEqual compact_hash_equal_;
KeyHashSet keys_;
std::vector<T> id2entry_;
const T *current_entry_;
};
template <class I, class T, class H, class E, HSType HS>
constexpr I CompactHashBiTable<I, T, H, E, HS>::kCurrentKey;
template <class I, class T, class H, class E, HSType HS>
constexpr I CompactHashBiTable<I, T, H, E, HS>::kEmptyKey;
template <class I, class T, class H, class E, HSType HS>
constexpr I CompactHashBiTable<I, T, H, E, HS>::kDeletedKey;
// An implementation using a vector for the entry to ID mapping. It is passed a
// function object FP that should fingerprint entries uniquely to an integer
// that can used as a vector index. Normally, VectorBiTable constructs the FP
// object. The user can instead pass in this object; in that case, VectorBiTable
// takes its ownership.
template <class I, class T, class FP>
class VectorBiTable {
public:
// Reserves table_size cells of space. If passing FP argument to the
// constructor, this class owns it.
explicit VectorBiTable(FP *fp = nullptr, size_t table_size = 0) :
fp_(fp ? fp : new FP()) {
if (table_size) id2entry_.reserve(table_size);
}
VectorBiTable(const VectorBiTable<I, T, FP> &table)
: fp_(new FP(*table.fp_)), fp2id_(table.fp2id_),
id2entry_(table.id2entry_) {}
I FindId(const T &entry, bool insert = true) {
ssize_t fp = (*fp_)(entry);
if (fp >= fp2id_.size()) fp2id_.resize(fp + 1);
I &id_ref = fp2id_[fp];
if (id_ref == 0) { // T not found.
if (insert) { // Stores and assigns a new ID.
id2entry_.push_back(entry);
id_ref = id2entry_.size();
} else {
return -1;
}
}
return id_ref - 1; // NB: id_ref = ID + 1.
}
const T &FindEntry(I s) const { return id2entry_[s]; }
I Size() const { return id2entry_.size(); }
const FP &Fingerprint() const { return *fp_; }
private:
std::unique_ptr<FP> fp_;
std::vector<I> fp2id_;
std::vector<T> id2entry_;
};
// An implementation using a vector and a compact hash table. The selecting
// functor S returns true for entries to be hashed in the vector. The
// fingerprinting functor FP returns a unique fingerprint for each entry to be
// hashed in the vector (these need to be suitable for indexing in a vector).
// The hash functor H is used when hashing entry into the compact hash table.
// If passed to the constructor, ownership is given to this class.
template <class I, class T, class S, class FP, class H, HSType HS = HS_DENSE>
class VectorHashBiTable {
public:
friend class HashFunc;
friend class HashEqual;
explicit VectorHashBiTable(S *s, FP *fp, H *h, size_t vector_size = 0,
size_t entry_size = 0)
: selector_(s), fp_(fp), h_(h), hash_func_(*this), hash_equal_(*this),
keys_(0, hash_func_, hash_equal_) {
if (vector_size) fp2id_.reserve(vector_size);
if (entry_size) id2entry_.reserve(entry_size);
}
VectorHashBiTable(const VectorHashBiTable<I, T, S, FP, H, HS> &table)
: selector_(new S(table.s_)), fp_(new FP(*table.fp_)),
h_(new H(*table.h_)), id2entry_(table.id2entry_),
fp2id_(table.fp2id_), hash_func_(*this), hash_equal_(*this),
keys_(table.keys_.size(), hash_func_, hash_equal_) {
keys_.insert(table.keys_.begin(), table.keys_.end());
}
I FindId(const T &entry, bool insert = true) {
if ((*selector_)(entry)) { // Uses the vector if selector_(entry) == true.
uint64 fp = (*fp_)(entry);
if (fp2id_.size() <= fp) fp2id_.resize(fp + 1, 0);
if (fp2id_[fp] == 0) { // T not found.
if (insert) { // Stores and assigns a new ID.
id2entry_.push_back(entry);
fp2id_[fp] = id2entry_.size();
} else {
return -1;
}
}
return fp2id_[fp] - 1; // NB: assoc_value = ID + 1.
} else { // Uses the hash table otherwise.
current_entry_ = &entry;
const auto it = keys_.find(kCurrentKey);
if (it == keys_.end()) {
if (insert) {
I key = id2entry_.size();
id2entry_.push_back(entry);
keys_.insert(key);
return key;
} else {
return -1;
}
} else {
return *it;
}
}
}
const T &FindEntry(I s) const { return id2entry_[s]; }
I Size() const { return id2entry_.size(); }
const S &Selector() const { return *selector_; }
const FP &Fingerprint() const { return *fp_; }
const H &Hash() const { return *h_; }
private:
static constexpr I kCurrentKey = -1;
static constexpr I kEmptyKey = -2;
class HashFunc {
public:
explicit HashFunc(const VectorHashBiTable &ht) : ht_(&ht) {}
size_t operator()(I k) const {
if (k >= kCurrentKey) {
return (*(ht_->h_))(ht_->Key2Entry(k));
} else {
return 0;
}
}
private:
const VectorHashBiTable *ht_;
};
class HashEqual {
public:
explicit HashEqual(const VectorHashBiTable &ht) : ht_(&ht) {}
bool operator()(I k1, I k2) const {
if (k1 >= kCurrentKey && k2 >= kCurrentKey) {
return ht_->Key2Entry(k1) == ht_->Key2Entry(k2);
} else {
return k1 == k2;
}
}
private:
const VectorHashBiTable *ht_;
};
using KeyHashSet = HashSet<I, HashFunc, HashEqual, HS>;
const T &Key2Entry(I k) const {
if (k == kCurrentKey) {
return *current_entry_;
} else {
return id2entry_[k];
}
}
std::unique_ptr<S> selector_; // True if entry hashed into vector.
std::unique_ptr<FP> fp_; // Fingerprint used for hashing into vector.
std::unique_ptr<H> h_; // Hash funcion used for hashing into hash_set.
std::vector<T> id2entry_; // Maps state IDs to entry.
std::vector<I> fp2id_; // Maps entry fingerprints to IDs.
// Compact implementation of the hash table mapping entries to state IDs
// using the hash function h_.
HashFunc hash_func_;
HashEqual hash_equal_;
KeyHashSet keys_;
const T *current_entry_;
};
template <class I, class T, class S, class FP, class H, HSType HS>
constexpr I VectorHashBiTable<I, T, S, FP, H, HS>::kCurrentKey;
template <class I, class T, class S, class FP, class H, HSType HS>
constexpr I VectorHashBiTable<I, T, S, FP, H, HS>::kEmptyKey;
// An implementation using a hash map for the entry to ID mapping. This version
// permits erasing of arbitrary states. The entry T must have == defined and
// its default constructor must produce a entry that will never be seen. F is
// the hash function.
template <class I, class T, class F>
class ErasableBiTable {
public:
ErasableBiTable() : first_(0) {}
I FindId(const T &entry, bool insert = true) {
I &id_ref = entry2id_[entry];
if (id_ref == 0) { // T not found.
if (insert) { // Stores and assigns a new ID.
id2entry_.push_back(entry);
id_ref = id2entry_.size() + first_;
} else {
return -1;
}
}
return id_ref - 1; // NB: id_ref = ID + 1.
}
const T &FindEntry(I s) const { return id2entry_[s - first_]; }
I Size() const { return id2entry_.size(); }
void Erase(I s) {
auto &ref = id2entry_[s - first_];
entry2id_.erase(ref);
ref = empty_entry_;
while (!id2entry_.empty() && id2entry_.front() == empty_entry_) {
id2entry_.pop_front();
++first_;
}
}
private:
std::unordered_map<T, I, F> entry2id_;
std::deque<T> id2entry_;
const T empty_entry_;
I first_; // I of first element in the deque.
};
} // namespace fst
#endif // FST_BI_TABLE_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/statesort.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Function to sort states of an FST.
#ifndef FST_STATESORT_H_
#define FST_STATESORT_H_
#include <algorithm>
#include <vector>
#include <fst/log.h>
#include <fst/mutable-fst.h>
namespace fst {
// Sorts the input states of an FST. order[i] gives the the state ID after
// sorting that corresponds to the state ID i before sorting; it must
// therefore be a permutation of the input FST's states ID sequence.
template <class Arc>
void StateSort(MutableFst<Arc> *fst,
const std::vector<typename Arc::StateId> &order) {
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
if (order.size() != fst->NumStates()) {
FSTERROR() << "StateSort: Bad order vector size: " << order.size();
fst->SetProperties(kError, kError);
return;
}
if (fst->Start() == kNoStateId) return;
const auto props = fst->Properties(kStateSortProperties, false);
std::vector<bool> done(order.size(), false);
std::vector<Arc> arcsa;
std::vector<Arc> arcsb;
fst->SetStart(order[fst->Start()]);
for (StateIterator<MutableFst<Arc>> siter(*fst); !siter.Done();
siter.Next()) {
auto s1 = siter.Value();
StateId s2;
if (done[s1]) continue;
auto final1 = fst->Final(s1);
auto final2 = Weight::Zero();
arcsa.clear();
for (ArcIterator<MutableFst<Arc>> aiter(*fst, s1); !aiter.Done();
aiter.Next()) {
arcsa.push_back(aiter.Value());
}
for (; !done[s1]; s1 = s2, final1 = final2, std::swap(arcsa, arcsb)) {
s2 = order[s1];
if (!done[s2]) {
final2 = fst->Final(s2);
arcsb.clear();
for (ArcIterator<MutableFst<Arc>> aiter(*fst, s2); !aiter.Done();
aiter.Next()) {
arcsb.push_back(aiter.Value());
}
}
fst->SetFinal(s2, final1);
fst->DeleteArcs(s2);
for (auto arc : arcsa) { // Copy intended.
arc.nextstate = order[arc.nextstate];
fst->AddArc(s2, arc);
}
done[s1] = true;
}
}
fst->SetProperties(props, kFstProperties);
}
} // namespace fst
#endif // FST_STATESORT_H_
| 0 |
coqui_public_repos/STT-models/german/yoummday | coqui_public_repos/STT-models/german/yoummday/v0.1.0/LICENSE | Attribution-NonCommercial 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
j. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
k. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
l. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/taskcluster/tc-update-index.sh | #!/bin/bash
# Helper script because it is way too painful to deal with Windows' CMD.exe
# ways of escaping things when pushing JSON
set -xe
TC_EXPIRE=$1
TC_INSTANCE=$2
TC_INDEX=$3
source $(dirname "$0")/tc-tests-utils.sh
if [ ! -z "${TC_EXPIRE}" -a ! -z "${TC_INSTANCE}" -a ! -z "${TC_INDEX}" ]; then
curl -sSL --fail -X PUT \
-H "Content-Type: application/json" \
-d "{\"taskId\":\"$TASK_ID\",\"rank\":0,\"expires\":\"${TC_EXPIRE}\",\"data\":{}}" \
"http://${TC_INSTANCE}/index/v1/task/${TC_INDEX}"
fi;
| 0 |
coqui_public_repos/STT/native_client/kenlm | coqui_public_repos/STT/native_client/kenlm/util/parallel_read.cc | #include "parallel_read.hh"
#include "file.hh"
#ifdef WITH_THREADS
#include "thread_pool.hh"
namespace util {
namespace {
class Reader {
public:
explicit Reader(int fd) : fd_(fd) {}
struct Request {
void *to;
std::size_t size;
uint64_t offset;
bool operator==(const Request &other) const {
return (to == other.to) && (size == other.size) && (offset == other.offset);
}
};
void operator()(const Request &request) {
util::ErsatzPRead(fd_, request.to, request.size, request.offset);
}
private:
int fd_;
};
} // namespace
void ParallelRead(int fd, void *to, std::size_t amount, uint64_t offset) {
Reader::Request poison;
poison.to = NULL;
poison.size = 0;
poison.offset = 0;
unsigned threads = boost::thread::hardware_concurrency();
if (!threads) threads = 2;
ThreadPool<Reader> pool(2 /* don't need much of a queue */, threads, fd, poison);
const std::size_t kBatch = 1ULL << 25; // 32 MB
Reader::Request request;
request.to = to;
request.size = kBatch;
request.offset = offset;
for (; amount > kBatch; amount -= kBatch) {
pool.Produce(request);
request.to = reinterpret_cast<uint8_t*>(request.to) + kBatch;
request.offset += kBatch;
}
request.size = amount;
if (request.size) {
pool.Produce(request);
}
}
} // namespace util
#else // WITH_THREADS
namespace util {
void ParallelRead(int fd, void *to, std::size_t amount, uint64_t offset) {
util::ErsatzPRead(fd, to, amount, offset);
}
} // namespace util
#endif
| 0 |
coqui_public_repos/STT/native_client/kenlm | coqui_public_repos/STT/native_client/kenlm/util/string_stream.hh | #ifndef UTIL_STRING_STREAM_H
#define UTIL_STRING_STREAM_H
#include "fake_ostream.hh"
#include <cassert>
#include <string>
namespace util {
class StringStream : public FakeOStream<StringStream> {
public:
StringStream() {}
StringStream &flush() { return *this; }
StringStream &write(const void *data, std::size_t length) {
out_.append(static_cast<const char*>(data), length);
return *this;
}
const std::string &str() const { return out_; }
void str(const std::string &val) { out_ = val; }
void swap(std::string &str) { std::swap(out_, str); }
protected:
friend class FakeOStream<StringStream>;
char *Ensure(std::size_t amount) {
std::size_t current = out_.size();
out_.resize(out_.size() + amount);
return &out_[current];
}
void AdvanceTo(char *to) {
assert(to <= &*out_.end());
assert(to >= &*out_.begin());
out_.resize(to - &*out_.begin());
}
private:
std::string out_;
};
} // namespace
#endif // UTIL_STRING_STREAM_H
| 0 |
coqui_public_repos/STT/native_client/kenlm/lm | coqui_public_repos/STT/native_client/kenlm/lm/interpolate/normalize.cc | #include "normalize.hh"
#include "../common/compare.hh"
#include "../common/ngram_stream.hh"
#include "backoff_matrix.hh"
#include "bounded_sequence_encoding.hh"
#include "interpolate_info.hh"
#include "merge_probabilities.hh"
#include "../weights.hh"
#include "../word_index.hh"
#include "../../util/fixed_array.hh"
#include "../../util/scoped.hh"
#include "../../util/stream/stream.hh"
#include "../../util/stream/rewindable_stream.hh"
#include <functional>
#include <queue>
#include <vector>
namespace lm { namespace interpolate {
namespace {
class BackoffQueueEntry {
public:
BackoffQueueEntry(float &entry, const util::stream::ChainPosition &position)
: entry_(entry), stream_(position) {
entry_ = 0.0;
}
operator bool() const { return stream_; }
NGramHeader operator*() const { return *stream_; }
const NGramHeader *operator->() const { return &*stream_; }
void Enter() {
entry_ = stream_->Value().backoff;
}
BackoffQueueEntry &Next() {
entry_ = 0.0;
++stream_;
return *this;
}
private:
float &entry_;
NGramStream<ProbBackoff> stream_;
};
struct PtrGreater : public std::binary_function<const BackoffQueueEntry *, const BackoffQueueEntry *, bool> {
bool operator()(const BackoffQueueEntry *first, const BackoffQueueEntry *second) const {
return SuffixLexicographicLess<NGramHeader>()(**second, **first);
}
};
class EntryOwner : public util::FixedArray<BackoffQueueEntry> {
public:
void push_back(float &entry, const util::stream::ChainPosition &position) {
new (end()) BackoffQueueEntry(entry, position);
Constructed();
}
};
std::size_t MaxOrder(const util::FixedArray<util::stream::ChainPositions> &model) {
std::size_t ret = 0;
for (const util::stream::ChainPositions *m = model.begin(); m != model.end(); ++m) {
ret = std::max(ret, m->size());
}
return ret;
}
class BackoffManager {
public:
explicit BackoffManager(const util::FixedArray<util::stream::ChainPositions> &models)
: entered_(MaxOrder(models)), matrix_(models.size(), MaxOrder(models)), skip_write_(MaxOrder(models)) {
std::size_t total = 0;
for (const util::stream::ChainPositions *m = models.begin(); m != models.end(); ++m) {
total += m->size();
}
for (std::size_t i = 0; i < MaxOrder(models); ++i) {
entered_.push_back(models.size());
}
owner_.Init(total);
for (const util::stream::ChainPositions *m = models.begin(); m != models.end(); ++m) {
for (const util::stream::ChainPosition *j = m->begin(); j != m->end(); ++j) {
owner_.push_back(matrix_.Backoff(m - models.begin(), j - m->begin()), *j);
if (owner_.back()) {
queue_.push(&owner_.back());
}
}
}
}
void SetupSkip(std::size_t order, util::stream::Stream &stream) {
skip_write_[order - 2] = &stream;
}
// Move up the backoffs for the given n-gram. The n-grams must be provided
// in suffix lexicographic order.
void Enter(const NGramHeader &to) {
// Check that we exited properly.
for (std::size_t i = to.Order() - 1; i < entered_.size(); ++i) {
assert(entered_[i].empty());
}
SuffixLexicographicLess<NGramHeader> less;
while (!queue_.empty() && less(**queue_.top(), to))
SkipRecord();
while (TopMatches(to)) {
BackoffQueueEntry *matches = queue_.top();
entered_[to.Order() - 1].push_back(matches);
matches->Enter();
queue_.pop();
}
}
void Exit(std::size_t order_minus_1) {
for (BackoffQueueEntry **i = entered_[order_minus_1].begin(); i != entered_[order_minus_1].end(); ++i) {
if ((*i)->Next())
queue_.push(*i);
}
entered_[order_minus_1].clear();
}
float Get(std::size_t model, std::size_t order_minus_1) const {
return matrix_.Backoff(model, order_minus_1);
}
void Finish() {
while (!queue_.empty())
SkipRecord();
}
private:
void SkipRecord() {
BackoffQueueEntry *top = queue_.top();
queue_.pop();
// Is this the last instance of the n-gram?
if (!TopMatches(**top)) {
// An n-gram is being skipped. Called once per skipped n-gram,
// regardless of how many models it comes from.
*reinterpret_cast<float*>(skip_write_[(*top)->Order() - 1]->Get()) = 0.0;
++*skip_write_[(*top)->Order() - 1];
}
if (top->Next())
queue_.push(top);
}
bool TopMatches(const NGramHeader &header) const {
return !queue_.empty() && (*queue_.top())->Order() == header.Order() && std::equal(header.begin(), header.end(), (*queue_.top())->begin());
}
EntryOwner owner_;
std::priority_queue<BackoffQueueEntry*, std::vector<BackoffQueueEntry*>, PtrGreater> queue_;
// Indexed by order then just all the matching models.
util::FixedArray<util::FixedArray<BackoffQueueEntry*> > entered_;
BackoffMatrix matrix_;
std::vector<util::stream::Stream*> skip_write_;
};
typedef long double Accum;
// Handles n-grams of the same order, using recursion to call another instance
// for higher orders.
class Recurse {
public:
Recurse(
const InterpolateInfo &info, // Must stay alive the entire time.
std::size_t order,
const util::stream::ChainPosition &merged_probs,
const util::stream::ChainPosition &prob_out,
const util::stream::ChainPosition &backoff_out,
BackoffManager &backoffs,
Recurse *higher) // higher is null for the highest order.
: order_(order),
encoding_(MakeEncoder(info, order)),
input_(merged_probs, PartialProbGamma(order, encoding_.EncodedLength())),
prob_out_(prob_out),
backoff_out_(backoff_out),
backoffs_(backoffs),
lambdas_(&*info.lambdas.begin()),
higher_(higher),
decoded_backoffs_(info.Models()),
extended_context_(order - 1) {
// This is only for bigrams and above. Summing unigrams is a much easier case.
assert(order >= 2);
}
// context = w_1^{n-1}
// z_lower = Z(w_2^{n-1})
// Input:
// Merged probabilities without backoff applied in input_.
// Backoffs via backoffs_.
// Calculates:
// Z(w_1^{n-1}): intermediate only.
// p_I(x | w_1^{n-1}) for all x: w_1^{n-1}x exists: Written to prob_out_.
// b_I(w_1^{n-1}): Written to backoff_out_.
void SameContext(const NGramHeader &context, Accum z_lower) {
assert(context.size() == order_ - 1);
backoffs_.Enter(context);
prob_out_.Mark();
// This is the backoff term that applies when one assumes everything backs off:
// \prod_i b_i(w_1^{n-1})^{\lambda_i}.
Accum backoff_once = 0.0;
for (std::size_t m = 0; m < decoded_backoffs_.size(); ++m) {
backoff_once += lambdas_[m] * backoffs_.Get(m, order_ - 2);
}
Accum z_delta = 0.0;
std::size_t count = 0;
for (; input_ && std::equal(context.begin(), context.end(), input_->begin()); ++input_, ++prob_out_, ++count) {
// Apply backoffs to probabilities.
// TODO: change bounded sequence encoding to have an iterator for decoding instead of doing a copy here.
encoding_.Decode(input_->FromBegin(), &*decoded_backoffs_.begin());
for (std::size_t m = 0; m < NumModels(); ++m) {
// Apply the backoffs as instructed for model m.
float accumulated = 0.0;
// Change backoffs for [order it backed off to, order - 1) except
// with 0-indexing. There is still the potential to charge backoff
// for order - 1, which is done later. The backoffs charged here
// are b_m(w_{n-1}^{n-1}) ... b_m(w_2^{n-1})
for (unsigned char backed_to = decoded_backoffs_[m]; backed_to < order_ - 2; ++backed_to) {
accumulated += backoffs_.Get(m, backed_to);
}
float lambda = lambdas_[m];
// Lower p(x | w_2^{n-1}) gets all the backoffs except the highest.
input_->LowerProb() += accumulated * lambda;
// Charge the backoff b(w_1^{n-1}) if applicable, but only to attain p(x | w_1^{n-1})
if (decoded_backoffs_[m] < order_ - 1) {
accumulated += backoffs_.Get(m, order_ - 2);
}
input_->Prob() += accumulated * lambda;
}
// TODO: better precision/less operations here.
z_delta += pow(10.0, input_->Prob()) - pow(10.0, input_->LowerProb() + backoff_once);
// Write unnormalized probability record.
std::copy(input_->begin(), input_->end(), reinterpret_cast<WordIndex*>(prob_out_.Get()));
ProbWrite() = input_->Prob();
}
// TODO numerical precision.
Accum z = log10(pow(10.0, z_lower + backoff_once) + z_delta);
// Normalize.
prob_out_.Rewind();
for (std::size_t i = 0; i < count; ++i, ++prob_out_) {
ProbWrite() -= z;
}
// This allows the stream to release data.
prob_out_.Mark();
// Output backoff.
*reinterpret_cast<float*>(backoff_out_.Get()) = z_lower + backoff_once - z;
++backoff_out_;
if (higher_.get())
higher_->ExtendContext(context, z);
backoffs_.Exit(order_ - 2);
}
// Call is given a context and z(context).
// Evaluates y context x for all y,x.
void ExtendContext(const NGramHeader &middle, Accum z_lower) {
assert(middle.size() == order_ - 2);
// Copy because the input will advance. TODO avoid this copy by sharing amongst classes.
std::copy(middle.begin(), middle.end(), extended_context_.begin() + 1);
while (input_ && std::equal(middle.begin(), middle.end(), input_->begin() + 1)) {
*extended_context_.begin() = *input_->begin();
SameContext(NGramHeader(&*extended_context_.begin(), order_ - 1), z_lower);
}
}
void Finish() {
assert(!input_);
prob_out_.Poison();
backoff_out_.Poison();
if (higher_.get())
higher_->Finish();
}
// The BackoffManager class also injects backoffs when it skips ahead e.g. b(</s>) = 1
util::stream::Stream &BackoffStream() { return backoff_out_; }
private:
// Write the probability to the correct place in prob_out_. Should use a proxy but currently incompatible with RewindableStream.
float &ProbWrite() {
return *reinterpret_cast<float*>(reinterpret_cast<uint8_t*>(prob_out_.Get()) + order_ * sizeof(WordIndex));
}
std::size_t NumModels() const { return decoded_backoffs_.size(); }
const std::size_t order_;
const BoundedSequenceEncoding encoding_;
ProxyStream<PartialProbGamma> input_;
util::stream::RewindableStream prob_out_;
util::stream::Stream backoff_out_;
BackoffManager &backoffs_;
const float *const lambdas_;
// Higher order instance of this same class.
util::scoped_ptr<Recurse> higher_;
// Temporary in SameContext.
std::vector<unsigned char> decoded_backoffs_;
// Temporary in ExtendContext.
std::vector<WordIndex> extended_context_;
};
class Thread {
public:
Thread(const InterpolateInfo &info, util::FixedArray<util::stream::ChainPositions> &models_by_order, util::stream::Chains &prob_out, util::stream::Chains &backoff_out)
: info_(info), models_by_order_(models_by_order), prob_out_(prob_out), backoff_out_(backoff_out) {}
void Run(const util::stream::ChainPositions &merged_probabilities) {
// Unigrams do not have enocded backoff info.
ProxyStream<PartialProbGamma> in(merged_probabilities[0], PartialProbGamma(1, 0));
util::stream::RewindableStream prob_write(prob_out_[0]);
Accum z = 0.0;
prob_write.Mark();
WordIndex count = 0;
for (; in; ++in, ++prob_write, ++count) {
// Note assumption that probabilitity comes first
memcpy(prob_write.Get(), in.Get(), sizeof(WordIndex) + sizeof(float));
z += pow(10.0, in->Prob());
}
// TODO HACK TODO: lmplz outputs p(<s>) = 1 to get q to compute nicely. That will always result in 1.0 more than it should be.
z -= 1.0;
float log_z = log10(z);
prob_write.Rewind();
// Normalize unigram probabilities.
for (WordIndex i = 0; i < count; ++i, ++prob_write) {
*reinterpret_cast<float*>(reinterpret_cast<uint8_t*>(prob_write.Get()) + sizeof(WordIndex)) -= log_z;
}
prob_write.Poison();
// Now setup the higher orders.
util::scoped_ptr<Recurse> higher_order;
BackoffManager backoffs(models_by_order_);
std::size_t max_order = merged_probabilities.size();
for (std::size_t order = max_order; order >= 2; --order) {
higher_order.reset(new Recurse(info_, order, merged_probabilities[order - 1], prob_out_[order - 1], backoff_out_[order - 2], backoffs, higher_order.release()));
backoffs.SetupSkip(order, higher_order->BackoffStream());
}
if (max_order > 1) {
higher_order->ExtendContext(NGramHeader(NULL, 0), log_z);
backoffs.Finish();
higher_order->Finish();
}
}
private:
const InterpolateInfo info_;
util::FixedArray<util::stream::ChainPositions> &models_by_order_;
util::stream::ChainPositions prob_out_;
util::stream::ChainPositions backoff_out_;
};
} // namespace
void Normalize(const InterpolateInfo &info, util::FixedArray<util::stream::ChainPositions> &models_by_order, util::stream::Chains &merged_probabilities, util::stream::Chains &prob_out, util::stream::Chains &backoff_out) {
assert(prob_out.size() == backoff_out.size() + 1);
// Arbitrarily put the thread on the merged_probabilities Chains.
merged_probabilities >> Thread(info, models_by_order, prob_out, backoff_out);
}
}} // namespaces
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/script/arcsort.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_SCRIPT_ARCSORT_H_
#define FST_SCRIPT_ARCSORT_H_
#include <utility>
#include <fst/arcsort.h>
#include <fst/script/fst-class.h>
namespace fst {
namespace script {
enum ArcSortType {
ILABEL_SORT,
OLABEL_SORT
};
using ArcSortArgs = std::pair<MutableFstClass *, ArcSortType>;
template <class Arc>
void ArcSort(ArcSortArgs *args) {
MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>();
switch (std::get<1>(*args)) {
case ILABEL_SORT: {
const ILabelCompare<Arc> icomp;
ArcSort(fst, icomp);
return;
}
case OLABEL_SORT: {
const OLabelCompare<Arc> ocomp;
ArcSort(fst, ocomp);
return;
}
}
}
void ArcSort(MutableFstClass *ofst, ArcSortType);
} // namespace script
} // namespace fst
#endif // FST_SCRIPT_ARCSORT_H_
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/taskcluster/test-nodejs_11x_16k-linux-amd64-opt.yml | build:
template_file: test-linux-opt-base.tyml
docker_image: "ubuntu:16.04"
dependencies:
- "linux-amd64-cpu-opt"
- "test-training_16k-linux-amd64-py36m-opt"
test_model_task: "test-training_16k-linux-amd64-py36m-opt"
system_setup:
>
${nodejs.packages_xenial.prep_11} && ${nodejs.packages_xenial.apt_pinning} && apt-get -qq update && apt-get -qq -y install ${nodejs.packages_xenial.apt}
args:
tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-node-tests.sh 11.x 16k"
workerType: "${docker.dsTests}"
metadata:
name: "DeepSpeech Linux AMD64 CPU NodeJS 11.x tests (16kHz)"
description: "Testing DeepSpeech for Linux/AMD64 on NodeJS v11.x, CPU only, optimized version (16kHz)"
| 0 |
coqui_public_repos/inference-engine/third_party/kenlm/lm | coqui_public_repos/inference-engine/third_party/kenlm/lm/interpolate/universal_vocab.cc | #include "lm/interpolate/universal_vocab.hh"
namespace lm {
namespace interpolate {
UniversalVocab::UniversalVocab(const std::vector<WordIndex>& model_vocab_sizes) {
model_index_map_.resize(model_vocab_sizes.size());
for (size_t i = 0; i < model_vocab_sizes.size(); ++i) {
model_index_map_[i].resize(model_vocab_sizes[i]);
}
}
}} // namespaces
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/product-weight.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Product weight set and associated semiring operation definitions.
#ifndef FST_PRODUCT_WEIGHT_H_
#define FST_PRODUCT_WEIGHT_H_
#include <string>
#include <utility>
#include <fst/pair-weight.h>
#include <fst/weight.h>
namespace fst {
// Product semiring: W1 * W2.
template <class W1, class W2>
class ProductWeight : public PairWeight<W1, W2> {
public:
using ReverseWeight =
ProductWeight<typename W1::ReverseWeight, typename W2::ReverseWeight>;
ProductWeight() {}
explicit ProductWeight(const PairWeight<W1, W2> &weight)
: PairWeight<W1, W2>(weight) {}
ProductWeight(W1 w1, W2 w2)
: PairWeight<W1, W2>(std::move(w1), std::move(w2)) {}
static const ProductWeight &Zero() {
static const ProductWeight zero(PairWeight<W1, W2>::Zero());
return zero;
}
static const ProductWeight &One() {
static const ProductWeight one(PairWeight<W1, W2>::One());
return one;
}
static const ProductWeight &NoWeight() {
static const ProductWeight no_weight(PairWeight<W1, W2>::NoWeight());
return no_weight;
}
static const string &Type() {
static const string *const type =
new string(W1::Type() + "_X_" + W2::Type());
return *type;
}
static constexpr uint64_t Properties() {
return W1::Properties() & W2::Properties() &
(kLeftSemiring | kRightSemiring | kCommutative | kIdempotent);
}
ProductWeight Quantize(float delta = kDelta) const {
return ProductWeight(PairWeight<W1, W2>::Quantize(delta));
}
ReverseWeight Reverse() const {
return ReverseWeight(PairWeight<W1, W2>::Reverse());
}
};
template <class W1, class W2>
inline ProductWeight<W1, W2> Plus(const ProductWeight<W1, W2> &w1,
const ProductWeight<W1, W2> &w2) {
return ProductWeight<W1, W2>(Plus(w1.Value1(), w2.Value1()),
Plus(w1.Value2(), w2.Value2()));
}
template <class W1, class W2>
inline ProductWeight<W1, W2> Times(const ProductWeight<W1, W2> &w1,
const ProductWeight<W1, W2> &w2) {
return ProductWeight<W1, W2>(Times(w1.Value1(), w2.Value1()),
Times(w1.Value2(), w2.Value2()));
}
template <class W1, class W2>
inline ProductWeight<W1, W2> Divide(const ProductWeight<W1, W2> &w1,
const ProductWeight<W1, W2> &w2,
DivideType typ = DIVIDE_ANY) {
return ProductWeight<W1, W2>(Divide(w1.Value1(), w2.Value1(), typ),
Divide(w1.Value2(), w2.Value2(), typ));
}
// This function object generates weights by calling the underlying generators
// for the template weight types, like all other pair weight types. This is
// intended primarily for testing.
template <class W1, class W2>
class WeightGenerate<ProductWeight<W1, W2>> :
public WeightGenerate<PairWeight<W1, W2>> {
public:
using Weight = ProductWeight<W1, W2>;
using Generate = WeightGenerate<PairWeight<W1, W2>>;
explicit WeightGenerate(bool allow_zero = true) : Generate(allow_zero) {}
Weight operator()() const { return Weight(Generate::operator()()); }
};
} // namespace fst
#endif // FST_PRODUCT_WEIGHT_H_
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/taskcluster/tf_linux-amd64-gpu_gcc9.yml.DISABLED | build:
template_file: generic_tc_caching-linux-opt-base.tyml
cache:
artifact_url: ${system.tensorflow_gcc9.linux_amd64_cuda.url}
artifact_namespace: ${system.tensorflow_gcc9.linux_amd64_cuda.namespace}
docker_image: "ubuntu:20.04"
system_config:
>
${tensorflow.packages_bionic.apt} && ${java.packages_bionic.apt}
scripts:
setup: "taskcluster/tf_tc-setup.sh --linux-cuda"
build: "taskcluster/tf_tc-build.sh --linux-cuda --py3"
package: "taskcluster/tf_tc-package.sh"
maxRunTime: 14400
workerType: "${docker.tfBuild}"
metadata:
name: "TensorFlow Linux AMD64 CUDA opt/gcc9"
description: "Building TensorFlow for Linux/AMD64, CUDA-enabled, opt/gcc9"
| 0 |
coqui_public_repos/TTS/TTS/encoder | coqui_public_repos/TTS/TTS/encoder/utils/training.py | import os
from dataclasses import dataclass, field
from coqpit import Coqpit
from trainer import TrainerArgs, get_last_checkpoint
from trainer.io import copy_model_files
from trainer.logging import logger_factory
from trainer.logging.console_logger import ConsoleLogger
from TTS.config import load_config, register_config
from TTS.tts.utils.text.characters import parse_symbols
from TTS.utils.generic_utils import get_experiment_folder_path, get_git_branch
@dataclass
class TrainArgs(TrainerArgs):
config_path: str = field(default=None, metadata={"help": "Path to the config file."})
def getarguments():
train_config = TrainArgs()
parser = train_config.init_argparse(arg_prefix="")
return parser
def process_args(args, config=None):
"""Process parsed comand line arguments and initialize the config if not provided.
Args:
args (argparse.Namespace or dict like): Parsed input arguments.
config (Coqpit): Model config. If none, it is generated from `args`. Defaults to None.
Returns:
c (TTS.utils.io.AttrDict): Config paramaters.
out_path (str): Path to save models and logging.
audio_path (str): Path to save generated test audios.
c_logger (TTS.utils.console_logger.ConsoleLogger): Class that does
logging to the console.
dashboard_logger (WandbLogger or TensorboardLogger): Class that does the dashboard Logging
TODO:
- Interactive config definition.
"""
if isinstance(args, tuple):
args, coqpit_overrides = args
if args.continue_path:
# continue a previous training from its output folder
experiment_path = args.continue_path
args.config_path = os.path.join(args.continue_path, "config.json")
args.restore_path, best_model = get_last_checkpoint(args.continue_path)
if not args.best_path:
args.best_path = best_model
# init config if not already defined
if config is None:
if args.config_path:
# init from a file
config = load_config(args.config_path)
else:
# init from console args
from TTS.config.shared_configs import BaseTrainingConfig # pylint: disable=import-outside-toplevel
config_base = BaseTrainingConfig()
config_base.parse_known_args(coqpit_overrides)
config = register_config(config_base.model)()
# override values from command-line args
config.parse_known_args(coqpit_overrides, relaxed_parser=True)
experiment_path = args.continue_path
if not experiment_path:
experiment_path = get_experiment_folder_path(config.output_path, config.run_name)
audio_path = os.path.join(experiment_path, "test_audios")
config.output_log_path = experiment_path
# setup rank 0 process in distributed training
dashboard_logger = None
if args.rank == 0:
new_fields = {}
if args.restore_path:
new_fields["restore_path"] = args.restore_path
new_fields["github_branch"] = get_git_branch()
# if model characters are not set in the config file
# save the default set to the config file for future
# compatibility.
if config.has("characters") and config.characters is None:
used_characters = parse_symbols()
new_fields["characters"] = used_characters
copy_model_files(config, experiment_path, new_fields)
dashboard_logger = logger_factory(config, experiment_path)
c_logger = ConsoleLogger()
return config, experiment_path, audio_path, c_logger, dashboard_logger
def init_arguments():
train_config = TrainArgs()
parser = train_config.init_argparse(arg_prefix="")
return parser
def init_training(config: Coqpit = None):
"""Initialization of a training run."""
parser = init_arguments()
args = parser.parse_known_args()
config, OUT_PATH, AUDIO_PATH, c_logger, dashboard_logger = process_args(args, config)
return args[0], config, OUT_PATH, AUDIO_PATH, c_logger, dashboard_logger
| 0 |
coqui_public_repos/STT/native_client/kenlm/lm | coqui_public_repos/STT/native_client/kenlm/lm/interpolate/universal_vocab.cc | #include "universal_vocab.hh"
namespace lm {
namespace interpolate {
UniversalVocab::UniversalVocab(const std::vector<WordIndex>& model_vocab_sizes) {
model_index_map_.resize(model_vocab_sizes.size());
for (size_t i = 0; i < model_vocab_sizes.size(); ++i) {
model_index_map_[i].resize(model_vocab_sizes[i]);
}
}
}} // namespaces
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/statesort.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Function to sort states of an FST.
#ifndef FST_STATESORT_H_
#define FST_STATESORT_H_
#include <algorithm>
#include <vector>
#include <fst/log.h>
#include <fst/mutable-fst.h>
namespace fst {
// Sorts the input states of an FST. order[i] gives the the state ID after
// sorting that corresponds to the state ID i before sorting; it must
// therefore be a permutation of the input FST's states ID sequence.
template <class Arc>
void StateSort(MutableFst<Arc> *fst,
const std::vector<typename Arc::StateId> &order) {
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
if (order.size() != fst->NumStates()) {
FSTERROR() << "StateSort: Bad order vector size: " << order.size();
fst->SetProperties(kError, kError);
return;
}
if (fst->Start() == kNoStateId) return;
const auto props = fst->Properties(kStateSortProperties, false);
std::vector<bool> done(order.size(), false);
std::vector<Arc> arcsa;
std::vector<Arc> arcsb;
fst->SetStart(order[fst->Start()]);
for (StateIterator<MutableFst<Arc>> siter(*fst); !siter.Done();
siter.Next()) {
auto s1 = siter.Value();
StateId s2;
if (done[s1]) continue;
auto final1 = fst->Final(s1);
auto final2 = Weight::Zero();
arcsa.clear();
for (ArcIterator<MutableFst<Arc>> aiter(*fst, s1); !aiter.Done();
aiter.Next()) {
arcsa.push_back(aiter.Value());
}
for (; !done[s1]; s1 = s2, final1 = final2, std::swap(arcsa, arcsb)) {
s2 = order[s1];
if (!done[s2]) {
final2 = fst->Final(s2);
arcsb.clear();
for (ArcIterator<MutableFst<Arc>> aiter(*fst, s2); !aiter.Done();
aiter.Next()) {
arcsb.push_back(aiter.Value());
}
}
fst->SetFinal(s2, final1);
fst->DeleteArcs(s2);
for (auto arc : arcsa) { // Copy intended.
arc.nextstate = order[arc.nextstate];
fst->AddArc(s2, arc);
}
done[s1] = true;
}
}
fst->SetProperties(props, kFstProperties);
}
} // namespace fst
#endif // FST_STATESORT_H_
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/bin/import_freestmandarin.py | #!/usr/bin/env python
import glob
import os
import tarfile
import numpy as np
import pandas
from coqui_stt_training.util.importers import get_importers_parser
COLUMN_NAMES = ["wav_filename", "wav_filesize", "transcript"]
def extract(archive_path, target_dir):
print("Extracting {} into {}...".format(archive_path, target_dir))
with tarfile.open(archive_path) as tar:
tar.extractall(target_dir)
def preprocess_data(tgz_file, target_dir):
# First extract main archive and sub-archives
extract(tgz_file, target_dir)
main_folder = os.path.join(target_dir, "ST-CMDS-20170001_1-OS")
# Folder structure is now:
# - ST-CMDS-20170001_1-OS/
# - *.wav
# - *.txt
# - *.metadata
def load_set(glob_path):
set_files = []
for wav in glob.glob(glob_path):
wav_filename = wav
wav_filesize = os.path.getsize(wav)
txt_filename = os.path.splitext(wav_filename)[0] + ".txt"
with open(txt_filename, "r") as fin:
transcript = fin.read()
set_files.append((wav_filename, wav_filesize, transcript))
return set_files
# Load all files, then deterministically split into train/dev/test sets
all_files = load_set(os.path.join(main_folder, "*.wav"))
df = pandas.DataFrame(data=all_files, columns=COLUMN_NAMES)
df.sort_values(by="wav_filename", inplace=True)
indices = np.arange(0, len(df))
np.random.seed(12345)
np.random.shuffle(indices)
# Total corpus size: 102600 samples. 5000 samples gives us 99% confidence
# level with a margin of error of under 2%.
test_indices = indices[-5000:]
dev_indices = indices[-10000:-5000]
train_indices = indices[:-10000]
train_files = df.iloc[train_indices]
durations = (train_files["wav_filesize"] - 44) / 16000 / 2
train_files = train_files[durations <= 10.0]
print("Trimming {} samples > 10 seconds".format((durations > 10.0).sum()))
dest_csv = os.path.join(target_dir, "freestmandarin_train.csv")
print("Saving train set into {}...".format(dest_csv))
train_files.to_csv(dest_csv, index=False)
dev_files = df.iloc[dev_indices]
dest_csv = os.path.join(target_dir, "freestmandarin_dev.csv")
print("Saving dev set into {}...".format(dest_csv))
dev_files.to_csv(dest_csv, index=False)
test_files = df.iloc[test_indices]
dest_csv = os.path.join(target_dir, "freestmandarin_test.csv")
print("Saving test set into {}...".format(dest_csv))
test_files.to_csv(dest_csv, index=False)
def main():
# https://www.openslr.org/38/
parser = get_importers_parser(description="Import Free ST Chinese Mandarin corpus")
parser.add_argument("tgz_file", help="Path to ST-CMDS-20170001_1-OS.tar.gz")
parser.add_argument(
"--target_dir",
default="",
help="Target folder to extract files into and put the resulting CSVs. Defaults to same folder as the main archive.",
)
params = parser.parse_args()
if not params.target_dir:
params.target_dir = os.path.dirname(params.tgz_file)
preprocess_data(params.tgz_file, params.target_dir)
if __name__ == "__main__":
main()
| 0 |
coqui_public_repos/STT-examples | coqui_public_repos/STT-examples/mic_vad_streaming/mic_vad_streaming.py | import time, logging
from datetime import datetime
import threading, collections, queue, os, os.path
import stt
import numpy as np
import pyaudio
import wave
import webrtcvad
from halo import Halo
from scipy import signal
logging.basicConfig(level=20)
class Audio(object):
"""Streams raw audio from microphone. Data is received in a separate thread, and stored in a buffer, to be read from."""
FORMAT = pyaudio.paInt16
# Network/VAD rate-space
RATE_PROCESS = 16000
CHANNELS = 1
BLOCKS_PER_SECOND = 50
def __init__(self, callback=None, device=None, input_rate=RATE_PROCESS, file=None):
def proxy_callback(in_data, frame_count, time_info, status):
#pylint: disable=unused-argument
if self.chunk is not None:
in_data = self.wf.readframes(self.chunk)
callback(in_data)
return (None, pyaudio.paContinue)
if callback is None: callback = lambda in_data: self.buffer_queue.put(in_data)
self.buffer_queue = queue.Queue()
self.device = device
self.input_rate = input_rate
self.sample_rate = self.RATE_PROCESS
self.block_size = int(self.RATE_PROCESS / float(self.BLOCKS_PER_SECOND))
self.block_size_input = int(self.input_rate / float(self.BLOCKS_PER_SECOND))
self.pa = pyaudio.PyAudio()
kwargs = {
'format': self.FORMAT,
'channels': self.CHANNELS,
'rate': self.input_rate,
'input': True,
'frames_per_buffer': self.block_size_input,
'stream_callback': proxy_callback,
}
self.chunk = None
# if not default device
if self.device:
kwargs['input_device_index'] = self.device
elif file is not None:
self.chunk = 320
self.wf = wave.open(file, 'rb')
self.stream = self.pa.open(**kwargs)
self.stream.start_stream()
def resample(self, data, input_rate):
"""
Microphone may not support our native processing sampling rate, so
resample from input_rate to RATE_PROCESS here for webrtcvad and
stt
Args:
data (binary): Input audio stream
input_rate (int): Input audio rate to resample from
"""
data16 = np.fromstring(string=data, dtype=np.int16)
resample_size = int(len(data16) / self.input_rate * self.RATE_PROCESS)
resample = signal.resample(data16, resample_size)
resample16 = np.array(resample, dtype=np.int16)
return resample16.tostring()
def read_resampled(self):
"""Return a block of audio data resampled to 16000hz, blocking if necessary."""
return self.resample(data=self.buffer_queue.get(),
input_rate=self.input_rate)
def read(self):
"""Return a block of audio data, blocking if necessary."""
return self.buffer_queue.get()
def destroy(self):
self.stream.stop_stream()
self.stream.close()
self.pa.terminate()
frame_duration_ms = property(lambda self: 1000 * self.block_size // self.sample_rate)
def write_wav(self, filename, data):
logging.info("write wav %s", filename)
wf = wave.open(filename, 'wb')
wf.setnchannels(self.CHANNELS)
# wf.setsampwidth(self.pa.get_sample_size(FORMAT))
assert self.FORMAT == pyaudio.paInt16
wf.setsampwidth(2)
wf.setframerate(self.sample_rate)
wf.writeframes(data)
wf.close()
class VADAudio(Audio):
"""Filter & segment audio with voice activity detection."""
def __init__(self, aggressiveness=3, device=None, input_rate=None, file=None):
super().__init__(device=device, input_rate=input_rate, file=file)
self.vad = webrtcvad.Vad(aggressiveness)
def frame_generator(self):
"""Generator that yields all audio frames from microphone."""
if self.input_rate == self.RATE_PROCESS:
while True:
yield self.read()
else:
while True:
yield self.read_resampled()
def vad_collector(self, padding_ms=300, ratio=0.75, frames=None):
"""Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None.
Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being triggered.
Example: (frame, ..., frame, None, frame, ..., frame, None, ...)
|---utterence---| |---utterence---|
"""
if frames is None: frames = self.frame_generator()
num_padding_frames = padding_ms // self.frame_duration_ms
ring_buffer = collections.deque(maxlen=num_padding_frames)
triggered = False
for frame in frames:
if len(frame) < 640:
return
is_speech = self.vad.is_speech(frame, self.sample_rate)
if not triggered:
ring_buffer.append((frame, is_speech))
num_voiced = len([f for f, speech in ring_buffer if speech])
if num_voiced > ratio * ring_buffer.maxlen:
triggered = True
for f, s in ring_buffer:
yield f
ring_buffer.clear()
else:
yield frame
ring_buffer.append((frame, is_speech))
num_unvoiced = len([f for f, speech in ring_buffer if not speech])
if num_unvoiced > ratio * ring_buffer.maxlen:
triggered = False
yield None
ring_buffer.clear()
def main(ARGS):
# Load STT model
if os.path.isdir(ARGS.model):
model_dir = ARGS.model
ARGS.model = os.path.join(model_dir, 'output_graph.pb')
ARGS.scorer = os.path.join(model_dir, ARGS.scorer)
print('Initializing model...')
logging.info("ARGS.model: %s", ARGS.model)
model = stt.Model(ARGS.model)
if ARGS.scorer:
logging.info("ARGS.scorer: %s", ARGS.scorer)
model.enableExternalScorer(ARGS.scorer)
# Start audio with VAD
vad_audio = VADAudio(aggressiveness=ARGS.vad_aggressiveness,
device=ARGS.device,
input_rate=ARGS.rate,
file=ARGS.file)
print("Listening (ctrl-C to exit)...")
frames = vad_audio.vad_collector()
# Stream from microphone to STT using VAD
spinner = None
if not ARGS.nospinner:
spinner = Halo(spinner='line')
stream_context = model.createStream()
wav_data = bytearray()
for frame in frames:
if frame is not None:
if spinner: spinner.start()
logging.debug("streaming frame")
stream_context.feedAudioContent(np.frombuffer(frame, np.int16))
if ARGS.savewav: wav_data.extend(frame)
else:
if spinner: spinner.stop()
logging.debug("end utterence")
if ARGS.savewav:
vad_audio.write_wav(os.path.join(ARGS.savewav, datetime.now().strftime("savewav_%Y-%m-%d_%H-%M-%S_%f.wav")), wav_data)
wav_data = bytearray()
text = stream_context.finishStream()
print("Recognized: %s" % text)
if ARGS.keyboard:
from pyautogui import typewrite
typewrite(text)
stream_context = model.createStream()
if __name__ == '__main__':
DEFAULT_SAMPLE_RATE = 16000
import argparse
parser = argparse.ArgumentParser(description="Stream from microphone to STT using VAD")
parser.add_argument('-v', '--vad_aggressiveness', type=int, default=3,
help="Set aggressiveness of VAD: an integer between 0 and 3, 0 being the least aggressive about filtering out non-speech, 3 the most aggressive. Default: 3")
parser.add_argument('--nospinner', action='store_true',
help="Disable spinner")
parser.add_argument('-w', '--savewav',
help="Save .wav files of utterences to given directory")
parser.add_argument('-f', '--file',
help="Read from .wav file instead of microphone")
parser.add_argument('-m', '--model', required=True,
help="Path to the model (protocol buffer binary file, or entire directory containing all standard-named files for model)")
parser.add_argument('-s', '--scorer',
help="Path to the external scorer file.")
parser.add_argument('-d', '--device', type=int, default=None,
help="Device input index (Int) as listed by pyaudio.PyAudio.get_device_info_by_index(). If not provided, falls back to PyAudio.get_default_device().")
parser.add_argument('-r', '--rate', type=int, default=DEFAULT_SAMPLE_RATE,
help=f"Input device sample rate. Default: {DEFAULT_SAMPLE_RATE}. Your device may require 44100.")
parser.add_argument('-k', '--keyboard', action='store_true',
help="Type output through system keyboard")
ARGS = parser.parse_args()
if ARGS.savewav: os.makedirs(ARGS.savewav, exist_ok=True)
main(ARGS)
| 0 |
coqui_public_repos/TTS/TTS/vc/modules/freevc | coqui_public_repos/TTS/TTS/vc/modules/freevc/wavlm/modules.py | # --------------------------------------------------------
# WavLM: Large-Scale Self-Supervised Pre-training for Full Stack Speech Processing (https://arxiv.org/abs/2110.13900.pdf)
# Github source: https://github.com/microsoft/unilm/tree/master/wavlm
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Based on fairseq code bases
# https://github.com/pytorch/fairseq
# --------------------------------------------------------
import math
import warnings
from typing import Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from torch.nn import Parameter
class TransposeLast(nn.Module):
def __init__(self, deconstruct_idx=None):
super().__init__()
self.deconstruct_idx = deconstruct_idx
def forward(self, x):
if self.deconstruct_idx is not None:
x = x[self.deconstruct_idx]
return x.transpose(-2, -1)
class Fp32LayerNorm(nn.LayerNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, input):
output = F.layer_norm(
input.float(),
self.normalized_shape,
self.weight.float() if self.weight is not None else None,
self.bias.float() if self.bias is not None else None,
self.eps,
)
return output.type_as(input)
class Fp32GroupNorm(nn.GroupNorm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def forward(self, input):
output = F.group_norm(
input.float(),
self.num_groups,
self.weight.float() if self.weight is not None else None,
self.bias.float() if self.bias is not None else None,
self.eps,
)
return output.type_as(input)
class GradMultiply(torch.autograd.Function):
@staticmethod
def forward(ctx, x, scale):
ctx.scale = scale
res = x.new(x)
return res
@staticmethod
def backward(ctx, grad):
return grad * ctx.scale, None
class SamePad(nn.Module):
def __init__(self, kernel_size, causal=False):
super().__init__()
if causal:
self.remove = kernel_size - 1
else:
self.remove = 1 if kernel_size % 2 == 0 else 0
def forward(self, x):
if self.remove > 0:
x = x[:, :, : -self.remove]
return x
class Swish(nn.Module):
"""Swish function"""
def __init__(self):
"""Construct an MultiHeadedAttention object."""
super(Swish, self).__init__()
self.act = torch.nn.Sigmoid()
def forward(self, x):
return x * self.act(x)
class GLU_Linear(nn.Module):
def __init__(self, input_dim, output_dim, glu_type="sigmoid", bias_in_glu=True):
super(GLU_Linear, self).__init__()
self.glu_type = glu_type
self.output_dim = output_dim
if glu_type == "sigmoid":
self.glu_act = torch.nn.Sigmoid()
elif glu_type == "swish":
self.glu_act = Swish()
elif glu_type == "relu":
self.glu_act = torch.nn.ReLU()
elif glu_type == "gelu":
self.glu_act = torch.nn.GELU()
if bias_in_glu:
self.linear = nn.Linear(input_dim, output_dim * 2, True)
else:
self.linear = nn.Linear(input_dim, output_dim * 2, False)
def forward(self, x):
# to be consistent with GLU_Linear, we assume the input always has the #channel (#dim) in the last dimension of the tensor, so need to switch the dimension first for 1D-Conv case
x = self.linear(x)
if self.glu_type == "bilinear":
x = x[:, :, 0 : self.output_dim] * x[:, :, self.output_dim : self.output_dim * 2]
else:
x = x[:, :, 0 : self.output_dim] * self.glu_act(x[:, :, self.output_dim : self.output_dim * 2])
return x
def gelu_accurate(x):
if not hasattr(gelu_accurate, "_a"):
gelu_accurate._a = math.sqrt(2 / math.pi)
return 0.5 * x * (1 + torch.tanh(gelu_accurate._a * (x + 0.044715 * torch.pow(x, 3))))
def gelu(x: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.gelu(x.float()).type_as(x)
def get_activation_fn(activation: str):
"""Returns the activation function corresponding to `activation`"""
if activation == "relu":
return F.relu
elif activation == "gelu":
return gelu
elif activation == "gelu_fast":
warnings.warn("--activation-fn=gelu_fast has been renamed to gelu_accurate")
return gelu_accurate
elif activation == "gelu_accurate":
return gelu_accurate
elif activation == "tanh":
return torch.tanh
elif activation == "linear":
return lambda x: x
elif activation == "glu":
return lambda x: x
else:
raise RuntimeError("--activation-fn {} not supported".format(activation))
def init_bert_params(module):
"""
Initialize the weights specific to the BERT Model.
This overrides the default initializations depending on the specified arguments.
1. If normal_init_linear_weights is set then weights of linear
layer will be initialized using the normal distribution and
bais will be set to the specified value.
2. If normal_init_embed_weights is set then weights of embedding
layer will be initialized using the normal distribution.
3. If normal_init_proj_weights is set then weights of
in_project_weight for MultiHeadAttention initialized using
the normal distribution (to be validated).
"""
def normal_(data):
# with FSDP, module params will be on CUDA, so we cast them back to CPU
# so that the RNG is consistent with and without FSDP
data.copy_(data.cpu().normal_(mean=0.0, std=0.02).to(data.device))
if isinstance(module, nn.Linear):
normal_(module.weight.data)
if module.bias is not None:
module.bias.data.zero_()
if isinstance(module, nn.Embedding):
normal_(module.weight.data)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
if isinstance(module, MultiheadAttention):
normal_(module.q_proj.weight.data)
normal_(module.k_proj.weight.data)
normal_(module.v_proj.weight.data)
def quant_noise(module, p, block_size):
"""
Wraps modules and applies quantization noise to the weights for
subsequent quantization with Iterative Product Quantization as
described in "Training with Quantization Noise for Extreme Model Compression"
Args:
- module: nn.Module
- p: amount of Quantization Noise
- block_size: size of the blocks for subsequent quantization with iPQ
Remarks:
- Module weights must have the right sizes wrt the block size
- Only Linear, Embedding and Conv2d modules are supported for the moment
- For more detail on how to quantize by blocks with convolutional weights,
see "And the Bit Goes Down: Revisiting the Quantization of Neural Networks"
- We implement the simplest form of noise here as stated in the paper
which consists in randomly dropping blocks
"""
# if no quantization noise, don't register hook
if p <= 0:
return module
# supported modules
assert isinstance(module, (nn.Linear, nn.Embedding, nn.Conv2d))
# test whether module.weight has the right sizes wrt block_size
is_conv = module.weight.ndim == 4
# 2D matrix
if not is_conv:
assert module.weight.size(1) % block_size == 0, "Input features must be a multiple of block sizes"
# 4D matrix
else:
# 1x1 convolutions
if module.kernel_size == (1, 1):
assert module.in_channels % block_size == 0, "Input channels must be a multiple of block sizes"
# regular convolutions
else:
k = module.kernel_size[0] * module.kernel_size[1]
assert k % block_size == 0, "Kernel size must be a multiple of block size"
def _forward_pre_hook(mod, input):
# no noise for evaluation
if mod.training:
if not is_conv:
# gather weight and sizes
weight = mod.weight
in_features = weight.size(1)
out_features = weight.size(0)
# split weight matrix into blocks and randomly drop selected blocks
mask = torch.zeros(in_features // block_size * out_features, device=weight.device)
mask.bernoulli_(p)
mask = mask.repeat_interleave(block_size, -1).view(-1, in_features)
else:
# gather weight and sizes
weight = mod.weight
in_channels = mod.in_channels
out_channels = mod.out_channels
# split weight matrix into blocks and randomly drop selected blocks
if mod.kernel_size == (1, 1):
mask = torch.zeros(
int(in_channels // block_size * out_channels),
device=weight.device,
)
mask.bernoulli_(p)
mask = mask.repeat_interleave(block_size, -1).view(-1, in_channels)
else:
mask = torch.zeros(weight.size(0), weight.size(1), device=weight.device)
mask.bernoulli_(p)
mask = mask.unsqueeze(2).unsqueeze(3).repeat(1, 1, mod.kernel_size[0], mod.kernel_size[1])
# scale weights and apply mask
mask = mask.to(torch.bool) # x.bool() is not currently supported in TorchScript
s = 1 / (1 - p)
mod.weight.data = s * weight.masked_fill(mask, 0)
module.register_forward_pre_hook(_forward_pre_hook)
return module
class MultiheadAttention(nn.Module):
"""Multi-headed attention.
See "Attention Is All You Need" for more details.
"""
def __init__(
self,
embed_dim,
num_heads,
kdim=None,
vdim=None,
dropout=0.0,
bias=True,
add_bias_kv=False,
add_zero_attn=False,
self_attention=False,
encoder_decoder_attention=False,
q_noise=0.0,
qn_block_size=8,
has_relative_attention_bias=False,
num_buckets=32,
max_distance=128,
gru_rel_pos=False,
rescale_init=False,
):
super().__init__()
self.embed_dim = embed_dim
self.kdim = kdim if kdim is not None else embed_dim
self.vdim = vdim if vdim is not None else embed_dim
self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
self.num_heads = num_heads
self.dropout_module = nn.Dropout(dropout)
self.has_relative_attention_bias = has_relative_attention_bias
self.num_buckets = num_buckets
self.max_distance = max_distance
if self.has_relative_attention_bias:
self.relative_attention_bias = nn.Embedding(num_buckets, num_heads)
self.head_dim = embed_dim // num_heads
self.q_head_dim = self.head_dim
self.k_head_dim = self.head_dim
assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
self.scaling = self.head_dim**-0.5
self.self_attention = self_attention
self.encoder_decoder_attention = encoder_decoder_attention
assert not self.self_attention or self.qkv_same_dim, (
"Self-attention requires query, key and " "value to be of the same size"
)
k_bias = True
if rescale_init:
k_bias = False
k_embed_dim = embed_dim
q_embed_dim = embed_dim
self.k_proj = quant_noise(nn.Linear(self.kdim, k_embed_dim, bias=k_bias), q_noise, qn_block_size)
self.v_proj = quant_noise(nn.Linear(self.vdim, embed_dim, bias=bias), q_noise, qn_block_size)
self.q_proj = quant_noise(nn.Linear(embed_dim, q_embed_dim, bias=bias), q_noise, qn_block_size)
self.out_proj = quant_noise(nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size)
if add_bias_kv:
self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
else:
self.bias_k = self.bias_v = None
self.add_zero_attn = add_zero_attn
self.gru_rel_pos = gru_rel_pos
if self.gru_rel_pos:
self.grep_linear = nn.Linear(self.q_head_dim, 8)
self.grep_a = nn.Parameter(torch.ones(1, num_heads, 1, 1))
self.reset_parameters()
def reset_parameters(self):
if self.qkv_same_dim:
# Empirically observed the convergence to be much better with
# the scaled initialization
nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
else:
nn.init.xavier_uniform_(self.k_proj.weight)
nn.init.xavier_uniform_(self.v_proj.weight)
nn.init.xavier_uniform_(self.q_proj.weight)
nn.init.xavier_uniform_(self.out_proj.weight)
if self.out_proj.bias is not None:
nn.init.constant_(self.out_proj.bias, 0.0)
if self.bias_k is not None:
nn.init.xavier_normal_(self.bias_k)
if self.bias_v is not None:
nn.init.xavier_normal_(self.bias_v)
if self.has_relative_attention_bias:
nn.init.xavier_normal_(self.relative_attention_bias.weight)
def _relative_positions_bucket(self, relative_positions, bidirectional=True):
num_buckets = self.num_buckets
max_distance = self.max_distance
relative_buckets = 0
if bidirectional:
num_buckets = num_buckets // 2
relative_buckets += (relative_positions > 0).to(torch.long) * num_buckets
relative_positions = torch.abs(relative_positions)
else:
relative_positions = -torch.min(relative_positions, torch.zeros_like(relative_positions))
max_exact = num_buckets // 2
is_small = relative_positions < max_exact
relative_postion_if_large = max_exact + (
torch.log(relative_positions.float() / max_exact)
/ math.log(max_distance / max_exact)
* (num_buckets - max_exact)
).to(torch.long)
relative_postion_if_large = torch.min(
relative_postion_if_large, torch.full_like(relative_postion_if_large, num_buckets - 1)
)
relative_buckets += torch.where(is_small, relative_positions, relative_postion_if_large)
return relative_buckets
def compute_bias(self, query_length, key_length):
context_position = torch.arange(query_length, dtype=torch.long)[:, None]
memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
relative_position = memory_position - context_position
relative_position_bucket = self._relative_positions_bucket(relative_position, bidirectional=True)
relative_position_bucket = relative_position_bucket.to(self.relative_attention_bias.weight.device)
values = self.relative_attention_bias(relative_position_bucket)
values = values.permute([2, 0, 1])
return values
def forward(
self,
query,
key: Optional[Tensor],
value: Optional[Tensor],
key_padding_mask: Optional[Tensor] = None,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
need_weights: bool = True,
static_kv: bool = False,
attn_mask: Optional[Tensor] = None,
before_softmax: bool = False,
need_head_weights: bool = False,
position_bias: Optional[Tensor] = None,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tensor]]:
"""Input shape: Time x Batch x Channel
Args:
key_padding_mask (ByteTensor, optional): mask to exclude
keys that are pads, of shape `(batch, src_len)`, where
padding elements are indicated by 1s.
need_weights (bool, optional): return the attention weights,
averaged over heads (default: False).
attn_mask (ByteTensor, optional): typically used to
implement causal attention, where the mask prevents the
attention from looking forward in time (default: None).
before_softmax (bool, optional): return the raw attention
weights and values before the attention softmax.
need_head_weights (bool, optional): return the attention
weights for each head. Implies *need_weights*. Default:
return the average attention weights over all heads.
"""
if need_head_weights:
need_weights = True
is_tpu = query.device.type == "xla"
tgt_len, bsz, embed_dim = query.size()
src_len = tgt_len
assert embed_dim == self.embed_dim
assert list(query.size()) == [tgt_len, bsz, embed_dim]
if key is not None:
src_len, key_bsz, _ = key.size()
if not torch.jit.is_scripting():
assert key_bsz == bsz
assert value is not None
assert src_len, bsz == value.shape[:2]
if self.has_relative_attention_bias and position_bias is None:
position_bias = self.compute_bias(tgt_len, src_len)
position_bias = position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, src_len)
if (
not is_tpu # don't use PyTorch version on TPUs
and incremental_state is None
and not static_kv
# A workaround for quantization to work. Otherwise JIT compilation
# treats bias in linear module as method.
and not torch.jit.is_scripting()
and self.q_head_dim == self.head_dim
):
assert key is not None and value is not None
assert attn_mask is None
attn_mask_rel_pos = None
if position_bias is not None:
attn_mask_rel_pos = position_bias
if self.gru_rel_pos:
query_layer = query.transpose(0, 1)
new_x_shape = query_layer.size()[:-1] + (self.num_heads, -1)
query_layer = query_layer.view(*new_x_shape)
query_layer = query_layer.permute(0, 2, 1, 3)
_B, _H, _L, __ = query_layer.size()
gate_a, gate_b = torch.sigmoid(
self.grep_linear(query_layer).view(_B, _H, _L, 2, 4).sum(-1, keepdim=False)
).chunk(2, dim=-1)
gate_a_1 = gate_a * (gate_b * self.grep_a - 1.0) + 2.0
attn_mask_rel_pos = gate_a_1.view(bsz * self.num_heads, -1, 1) * position_bias
attn_mask_rel_pos = attn_mask_rel_pos.view((-1, tgt_len, tgt_len))
k_proj_bias = self.k_proj.bias
if k_proj_bias is None:
k_proj_bias = torch.zeros_like(self.q_proj.bias)
x, attn = F.multi_head_attention_forward(
query,
key,
value,
self.embed_dim,
self.num_heads,
torch.empty([0]),
torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
self.bias_k,
self.bias_v,
self.add_zero_attn,
self.dropout_module.p,
self.out_proj.weight,
self.out_proj.bias,
self.training,
# self.training or self.dropout_module.apply_during_inference,
key_padding_mask,
need_weights,
attn_mask_rel_pos,
use_separate_proj_weight=True,
q_proj_weight=self.q_proj.weight,
k_proj_weight=self.k_proj.weight,
v_proj_weight=self.v_proj.weight,
)
return x, attn, position_bias
if incremental_state is not None:
saved_state = self._get_input_buffer(incremental_state)
if saved_state is not None and "prev_key" in saved_state:
# previous time steps are cached - no need to recompute
# key and value if they are static
if static_kv:
assert self.encoder_decoder_attention and not self.self_attention
key = value = None
else:
saved_state = None
if self.self_attention:
q = self.q_proj(query)
k = self.k_proj(query)
v = self.v_proj(query)
elif self.encoder_decoder_attention:
# encoder-decoder attention
q = self.q_proj(query)
if key is None:
assert value is None
k = v = None
else:
k = self.k_proj(key)
v = self.v_proj(key)
else:
assert key is not None and value is not None
q = self.q_proj(query)
k = self.k_proj(key)
v = self.v_proj(value)
q *= self.scaling
if self.bias_k is not None:
assert self.bias_v is not None
k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
if attn_mask is not None:
attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1)
if key_padding_mask is not None:
key_padding_mask = torch.cat(
[
key_padding_mask,
key_padding_mask.new_zeros(key_padding_mask.size(0), 1),
],
dim=1,
)
q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.q_head_dim).transpose(0, 1)
if k is not None:
k = k.contiguous().view(-1, bsz * self.num_heads, self.k_head_dim).transpose(0, 1)
if v is not None:
v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
if saved_state is not None:
# saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
if "prev_key" in saved_state:
_prev_key = saved_state["prev_key"]
assert _prev_key is not None
prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)
if static_kv:
k = prev_key
else:
assert k is not None
k = torch.cat([prev_key, k], dim=1)
src_len = k.size(1)
if "prev_value" in saved_state:
_prev_value = saved_state["prev_value"]
assert _prev_value is not None
prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)
if static_kv:
v = prev_value
else:
assert v is not None
v = torch.cat([prev_value, v], dim=1)
prev_key_padding_mask: Optional[Tensor] = None
if "prev_key_padding_mask" in saved_state:
prev_key_padding_mask = saved_state["prev_key_padding_mask"]
assert k is not None and v is not None
key_padding_mask = MultiheadAttention._append_prev_key_padding_mask(
key_padding_mask=key_padding_mask,
prev_key_padding_mask=prev_key_padding_mask,
batch_size=bsz,
src_len=k.size(1),
static_kv=static_kv,
)
saved_state["prev_key"] = k.view(bsz, self.num_heads, -1, self.head_dim)
saved_state["prev_value"] = v.view(bsz, self.num_heads, -1, self.head_dim)
saved_state["prev_key_padding_mask"] = key_padding_mask
# In this branch incremental_state is never None
assert incremental_state is not None
incremental_state = self._set_input_buffer(incremental_state, saved_state)
assert k is not None
assert k.size(1) == src_len
# This is part of a workaround to get around fork/join parallelism
# not supporting Optional types.
if key_padding_mask is not None and key_padding_mask.dim() == 0:
key_padding_mask = None
if key_padding_mask is not None:
assert key_padding_mask.size(0) == bsz
assert key_padding_mask.size(1) == src_len
if self.add_zero_attn:
assert v is not None
src_len += 1
k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)
v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)
if attn_mask is not None:
attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1)
if key_padding_mask is not None:
key_padding_mask = torch.cat(
[
key_padding_mask,
torch.zeros(key_padding_mask.size(0), 1).type_as(key_padding_mask),
],
dim=1,
)
attn_weights = torch.bmm(q, k.transpose(1, 2))
attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
if attn_mask is not None:
attn_mask = attn_mask.unsqueeze(0)
attn_weights += attn_mask
if key_padding_mask is not None:
# don't attend to padding symbols
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
if not is_tpu:
attn_weights = attn_weights.masked_fill(
key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),
float("-inf"),
)
else:
attn_weights = attn_weights.transpose(0, 2)
attn_weights = attn_weights.masked_fill(key_padding_mask, float("-inf"))
attn_weights = attn_weights.transpose(0, 2)
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
if before_softmax:
return attn_weights, v, position_bias
if position_bias is not None:
if self.gru_rel_pos == 1:
query_layer = q.view(bsz, self.num_heads, tgt_len, self.q_head_dim)
_B, _H, _L, __ = query_layer.size()
gate_a, gate_b = torch.sigmoid(
self.grep_linear(query_layer).view(_B, _H, _L, 2, 4).sum(-1, keepdim=False)
).chunk(2, dim=-1)
gate_a_1 = gate_a * (gate_b * self.grep_a - 1.0) + 2.0
position_bias = gate_a_1.view(bsz * self.num_heads, -1, 1) * position_bias
position_bias = position_bias.view(attn_weights.size())
attn_weights = attn_weights + position_bias
attn_weights_float = F.softmax(attn_weights, dim=-1)
attn_weights = attn_weights_float.type_as(attn_weights)
attn_probs = self.dropout_module(attn_weights)
assert v is not None
attn = torch.bmm(attn_probs, v)
assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
attn = self.out_proj(attn)
attn_weights: Optional[Tensor] = None
if need_weights:
attn_weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0)
if not need_head_weights:
# average attention weights over heads
attn_weights = attn_weights.mean(dim=0)
return attn, attn_weights, position_bias
@staticmethod
def _append_prev_key_padding_mask(
key_padding_mask: Optional[Tensor],
prev_key_padding_mask: Optional[Tensor],
batch_size: int,
src_len: int,
static_kv: bool,
) -> Optional[Tensor]:
# saved key padding masks have shape (bsz, seq_len)
if prev_key_padding_mask is not None and static_kv:
new_key_padding_mask = prev_key_padding_mask
elif prev_key_padding_mask is not None and key_padding_mask is not None:
new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), key_padding_mask.float()], dim=1)
# During incremental decoding, as the padding token enters and
# leaves the frame, there will be a time when prev or current
# is None
elif prev_key_padding_mask is not None:
if src_len > prev_key_padding_mask.size(1):
filler = torch.zeros(
(batch_size, src_len - prev_key_padding_mask.size(1)),
device=prev_key_padding_mask.device,
)
new_key_padding_mask = torch.cat([prev_key_padding_mask.float(), filler.float()], dim=1)
else:
new_key_padding_mask = prev_key_padding_mask.float()
elif key_padding_mask is not None:
if src_len > key_padding_mask.size(1):
filler = torch.zeros(
(batch_size, src_len - key_padding_mask.size(1)),
device=key_padding_mask.device,
)
new_key_padding_mask = torch.cat([filler.float(), key_padding_mask.float()], dim=1)
else:
new_key_padding_mask = key_padding_mask.float()
else:
new_key_padding_mask = prev_key_padding_mask
return new_key_padding_mask
def _get_input_buffer(
self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]
) -> Dict[str, Optional[Tensor]]:
result = self.get_incremental_state(incremental_state, "attn_state")
if result is not None:
return result
else:
empty_result: Dict[str, Optional[Tensor]] = {}
return empty_result
def _set_input_buffer(
self,
incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
buffer: Dict[str, Optional[Tensor]],
):
return self.set_incremental_state(incremental_state, "attn_state", buffer)
def apply_sparse_mask(self, attn_weights, tgt_len: int, src_len: int, bsz: int):
return attn_weights
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions/special/Makefile.am | AM_CPPFLAGS = -I$(srcdir)/../../include $(ICU_CPPFLAGS)
if HAVE_BIN
bin_PROGRAMS = fstspecial
LDADD = ../../script/libfstscript.la \
../../lib/libfst.la -lm $(DL_LIBS)
fstspecial_SOURCES = ../../bin/fstconvert.cc ../../bin/fstconvert-main.cc \
phi-fst.cc rho-fst.cc sigma-fst.cc
fstspecial_CPPFLAGS = $(AM_CPPFLAGS)
endif
libfstdir = @libfstdir@
libfst_LTLIBRARIES = phi-fst.la rho-fst.la sigma-fst.la
lib_LTLIBRARIES = libfstspecial.la
libfstspecial_la_SOURCES = phi-fst.cc rho-fst.cc sigma-fst.cc
libfstspecial_la_LDFLAGS = -version-info 10:0:0 -lm $(DL_LIBS)
libfstspecial_la_LIBADD = ../../lib/libfst.la -lm $(DL_LIBS)
phi_fst_la_SOURCES = phi-fst.cc
phi_fst_la_LDFLAGS = -module
phi_fst_la_LIBADD = ../../lib/libfst.la -lm $(DL_LIBS)
rho_fst_la_SOURCES = rho-fst.cc
rho_fst_la_LDFLAGS = -module
rho_fst_la_LIBADD = ../../lib/libfst.la -lm $(DL_LIBS)
sigma_fst_la_SOURCES = sigma-fst.cc
sigma_fst_la_LDFLAGS = -module
sigma_fst_la_LIBADD = ../../lib/libfst.la -lm $(DL_LIBS)
| 0 |
coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external | coqui_public_repos/inference-engine/third_party/cereal/include/cereal/external/rapidxml/manual.html | <html><head><style type="text/css">
body
{
font-family: sans-serif;
font-size: 90%;
margin: 8pt 8pt 8pt 8pt;
text-align: justify;
background-color: White;
}
h1 { font-weight: bold; text-align: left; }
h2 { font: 140% sans-serif; font-weight: bold; text-align: left; }
h3 { font: 120% sans-serif; font-weight: bold; text-align: left; }
h4 { font: bold 100% sans-serif; font-weight: bold; text-align: left; }
h5 { font: italic 100% sans-serif; font-weight: bold; text-align: left; }
h6 { font: small-caps 100% sans-serif; font-weight: bold; text-align: left; }
code
{
font-family: "Courier New", Courier, mono;
}
pre
{
border-top: gray 0.5pt solid;
border-right: gray 0.5pt solid;
border-left: gray 0.5pt solid;
border-bottom: gray 0.5pt solid;
padding-top: 2pt;
padding-right: 2pt;
padding-left: 2pt;
padding-bottom: 2pt;
display: block;
font-family: "courier new", courier, mono;
background-color: #eeeeee;
}
a
{
color: #000080;
text-decoration: none;
}
a:hover
{
text-decoration: underline;
}
.reference-header
{
border-top: gray 0.5pt solid;
border-right: gray 0.5pt solid;
border-left: gray 0.5pt solid;
border-bottom: gray 0.5pt solid;
padding-top: 2pt;
padding-right: 2pt;
padding-left: 2pt;
padding-bottom: 2pt;
background-color: #dedede;
}
.parameter-name
{
font-style: italic;
}
.indented
{
margin-left: 0.5cm;
}
a.toc1
{
margin-left: 0.0cm;
}
a.toc2
{
margin-left: 0.75cm;
}
a.toc3
{
margin-left: 1.5cm;
}
</style></head><body><h1>RAPIDXML Manual</h1><h3>Version 1.13</h3><detaileddescription xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><para><i>Copyright (C) 2006, 2009 Marcin Kalicinski</i><br/><i>See accompanying file <a href="license.txt">license.txt</a> for license information.</i><hr/><h2 level="2">Table of Contents</h2></para><para><toc><toc-contents><a href="#namespacerapidxml_1what_is_rapidxml" class="toc1">1. What is RapidXml?</a><br/><a href="#namespacerapidxml_1dependencies_and_compatibility" class="toc2">1.1 Dependencies And Compatibility</a><br/><a href="#namespacerapidxml_1character_types_and_encodings" class="toc2">1.2 Character Types And Encodings</a><br/><a href="#namespacerapidxml_1error_handling" class="toc2">1.3 Error Handling</a><br/><a href="#namespacerapidxml_1memory_allocation" class="toc2">1.4 Memory Allocation</a><br/><a href="#namespacerapidxml_1w3c_compliance" class="toc2">1.5 W3C Compliance</a><br/><a href="#namespacerapidxml_1api_design" class="toc2">1.6 API Design</a><br/><a href="#namespacerapidxml_1reliability" class="toc2">1.7 Reliability</a><br/><a href="#namespacerapidxml_1acknowledgements" class="toc2">1.8 Acknowledgements</a><br/><a href="#namespacerapidxml_1two_minute_tutorial" class="toc1">2. Two Minute Tutorial</a><br/><a href="#namespacerapidxml_1parsing" class="toc2">2.1 Parsing</a><br/><a href="#namespacerapidxml_1accessing_dom_tree" class="toc2">2.2 Accessing The DOM Tree</a><br/><a href="#namespacerapidxml_1modifying_dom_tree" class="toc2">2.3 Modifying The DOM Tree</a><br/><a href="#namespacerapidxml_1printing" class="toc2">2.4 Printing XML</a><br/><a href="#namespacerapidxml_1differences" class="toc1">3. Differences From Regular XML Parsers</a><br/><a href="#namespacerapidxml_1lifetime_of_source_text" class="toc2">3.1 Lifetime Of Source Text</a><br/><a href="#namespacerapidxml_1ownership_of_strings" class="toc2">3.2 Ownership Of Strings</a><br/><a href="#namespacerapidxml_1destructive_non_destructive" class="toc2">3.3 Destructive Vs Non-Destructive Mode</a><br/><a href="#namespacerapidxml_1performance" class="toc1">4. Performance</a><br/><a href="#namespacerapidxml_1performance_charts" class="toc2">4.1 Comparison With Other Parsers</a><br/><a href="#namespacerapidxml_1reference" class="toc1">5. Reference</a><br/></toc-contents></toc><br/></para><sect1><h2 id="namespacerapidxml_1what_is_rapidxml">1. What is RapidXml?</h2><para><a href="http://rapidxml.sourceforge.net">RapidXml</a> is an attempt to create the fastest XML DOM parser possible, while retaining useability, portability and reasonable W3C compatibility. It is an in-situ parser written in C++, with parsing speed approaching that of <code>strlen()</code> function executed on the same data. <br/><br/>
Entire parser is contained in a single header file, so no building or linking is neccesary. To use it you just need to copy <code>rapidxml.hpp</code> file to a convenient place (such as your project directory), and include it where needed. You may also want to use printing functions contained in header <code>rapidxml_print.hpp</code>.</para><sect2><h3 id="namespacerapidxml_1dependencies_and_compatibility">1.1 Dependencies And Compatibility</h3><para>RapidXml has <i>no dependencies</i> other than a very small subset of standard C++ library (<code><cassert></code>, <code><cstdlib></code>, <code><new></code> and <code><exception></code>, unless exceptions are disabled). It should compile on any reasonably conformant compiler, and was tested on Visual C++ 2003, Visual C++ 2005, Visual C++ 2008, gcc 3, gcc 4, and Comeau 4.3.3. Care was taken that no warnings are produced on these compilers, even with highest warning levels enabled.</para></sect2><sect2><h3 id="namespacerapidxml_1character_types_and_encodings">1.2 Character Types And Encodings</h3><para>RapidXml is character type agnostic, and can work both with narrow and wide characters. Current version does not fully support UTF-16 or UTF-32, so use of wide characters is somewhat incapacitated. However, it should succesfully parse <code>wchar_t</code> strings containing UTF-16 or UTF-32 if endianness of the data matches that of the machine. UTF-8 is fully supported, including all numeric character references, which are expanded into appropriate UTF-8 byte sequences (unless you enable parse_no_utf8 flag). <br/><br/>
Note that RapidXml performs no decoding - strings returned by name() and value() functions will contain text encoded using the same encoding as source file. Rapidxml understands and expands the following character references: <code>&apos; &amp; &quot; &lt; &gt; &#...;</code> Other character references are not expanded.</para></sect2><sect2><h3 id="namespacerapidxml_1error_handling">1.3 Error Handling</h3><para>By default, RapidXml uses C++ exceptions to report errors. If this behaviour is undesirable, RAPIDXML_NO_EXCEPTIONS can be defined to suppress exception code. See <a href="#classrapidxml_1_1parse__error" kindref="compound">parse_error</a> class and <a href="#namespacerapidxml_ff5d67f74437199d316d2b2660653ae1_1ff5d67f74437199d316d2b2660653ae1" kindref="member">parse_error_handler()</a> function for more information.</para></sect2><sect2><h3 id="namespacerapidxml_1memory_allocation">1.4 Memory Allocation</h3><para>RapidXml uses a special memory pool object to allocate nodes and attributes, because direct allocation using <code>new</code> operator would be far too slow. Underlying memory allocations performed by the pool can be customized by use of <a href="#classrapidxml_1_1memory__pool_c0a55a6ef0837dca67572e357100d78a_1c0a55a6ef0837dca67572e357100d78a" kindref="member">memory_pool::set_allocator()</a> function. See class <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> for more information.</para></sect2><sect2><h3 id="namespacerapidxml_1w3c_compliance">1.5 W3C Compliance</h3><para>RapidXml is not a W3C compliant parser, primarily because it ignores DOCTYPE declarations. There is a number of other, minor incompatibilities as well. Still, it can successfully parse and produce complete trees of all valid XML files in W3C conformance suite (over 1000 files specially designed to find flaws in XML processors). In destructive mode it performs whitespace normalization and character entity substitution for a small set of built-in entities.</para></sect2><sect2><h3 id="namespacerapidxml_1api_design">1.6 API Design</h3><para>RapidXml API is minimalistic, to reduce code size as much as possible, and facilitate use in embedded environments. Additional convenience functions are provided in separate headers: <code>rapidxml_utils.hpp</code> and <code><a href="#rapidxml__print_8hpp" kindref="compound">rapidxml_print.hpp</a></code>. Contents of these headers is not an essential part of the library, and is currently not documented (otherwise than with comments in code).</para></sect2><sect2><h3 id="namespacerapidxml_1reliability">1.7 Reliability</h3><para>RapidXml is very robust and comes with a large harness of unit tests. Special care has been taken to ensure stability of the parser no matter what source text is thrown at it. One of the unit tests produces 100,000 randomly corrupted variants of XML document, which (when uncorrupted) contains all constructs recognized by RapidXml. RapidXml passes this test when it correctly recognizes that errors have been introduced, and does not crash or loop indefinitely. <br/><br/>
Another unit test puts RapidXml head-to-head with another, well estabilished XML parser, and verifies that their outputs match across a wide variety of small and large documents. <br/><br/>
Yet another test feeds RapidXml with over 1000 test files from W3C compliance suite, and verifies that correct results are obtained. There are also additional tests that verify each API function separately, and test that various parsing modes work as expected.</para></sect2><sect2><h3 id="namespacerapidxml_1acknowledgements">1.8 Acknowledgements</h3><para>I would like to thank Arseny Kapoulkine for his work on <a href="http://code.google.com/p/pugixml">pugixml</a>, which was an inspiration for this project. Additional thanks go to Kristen Wegner for creating <a href="http://www.codeproject.com/soap/pugxml.asp">pugxml</a>, from which pugixml was derived. Janusz Wohlfeil kindly ran RapidXml speed tests on hardware that I did not have access to, allowing me to expand performance comparison table.</para></sect2></sect1><sect1><h2 id="namespacerapidxml_1two_minute_tutorial">2. Two Minute Tutorial</h2><sect2><h3 id="namespacerapidxml_1parsing">2.1 Parsing</h3><para>The following code causes RapidXml to parse a zero-terminated string named <code>text</code>: <pre>using namespace rapidxml;
xml_document<> doc; // character type defaults to char
doc.parse<0>(text); // 0 means default parse flags
</pre><code>doc</code> object is now a root of DOM tree containing representation of the parsed XML. Because all RapidXml interface is contained inside namespace <code>rapidxml</code>, users must either bring contents of this namespace into scope, or fully qualify all the names. Class <a href="#classrapidxml_1_1xml__document" kindref="compound">xml_document</a> represents a root of the DOM hierarchy. By means of public inheritance, it is also an <a href="#classrapidxml_1_1xml__node" kindref="compound">xml_node</a> and a <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a>. Template parameter of <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function is used to specify parsing flags, with which you can fine-tune behaviour of the parser. Note that flags must be a compile-time constant.</para></sect2><sect2><h3 id="namespacerapidxml_1accessing_dom_tree">2.2 Accessing The DOM Tree</h3><para>To access the DOM tree, use methods of <a href="#classrapidxml_1_1xml__node" kindref="compound">xml_node</a> and <a href="#classrapidxml_1_1xml__attribute" kindref="compound">xml_attribute</a> classes: <pre>cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
xml_node<> *node = doc.first_node("foobar");
cout << "Node foobar has value " << node->value() << "\n";
for (xml_attribute<> *attr = node->first_attribute();
attr; attr = attr->next_attribute())
{
cout << "Node foobar has attribute " << attr->name() << " ";
cout << "with value " << attr->value() << "\n";
}
</pre></para></sect2><sect2><h3 id="namespacerapidxml_1modifying_dom_tree">2.3 Modifying The DOM Tree</h3><para>DOM tree produced by the parser is fully modifiable. Nodes and attributes can be added/removed, and their contents changed. The below example creates a HTML document, whose sole contents is a link to google.com website: <pre>xml_document<> doc;
xml_node<> *node = doc.allocate_node(node_element, "a", "Google");
doc.append_node(node);
xml_attribute<> *attr = doc.allocate_attribute("href", "google.com");
node->append_attribute(attr);
</pre> One quirk is that nodes and attributes <i>do not own</i> the text of their names and values. This is because normally they only store pointers to the source text. So, when assigning a new name or value to the node, care must be taken to ensure proper lifetime of the string. The easiest way to achieve it is to allocate the string from the <a href="#classrapidxml_1_1xml__document" kindref="compound">xml_document</a> memory pool. In the above example this is not necessary, because we are only assigning character constants. But the code below uses <a href="#classrapidxml_1_1memory__pool_69729185bc59b0875192d667c47b8859_169729185bc59b0875192d667c47b8859" kindref="member">memory_pool::allocate_string()</a> function to allocate node name (which will have the same lifetime as the document), and assigns it to a new node: <pre>xml_document<> doc;
char *node_name = doc.allocate_string(name); // Allocate string and copy name into it
xml_node<> *node = doc.allocate_node(node_element, node_name); // Set node name to node_name
</pre> Check <a href="#namespacerapidxml_1reference" kindref="member">Reference</a> section for description of the entire interface.</para></sect2><sect2><h3 id="namespacerapidxml_1printing">2.4 Printing XML</h3><para>You can print <code><a href="#classrapidxml_1_1xml__document" kindref="compound">xml_document</a></code> and <code><a href="#classrapidxml_1_1xml__node" kindref="compound">xml_node</a></code> objects into an XML string. Use <a href="#namespacerapidxml_b94d570fc4c4ab2423813cd0243326b1_1b94d570fc4c4ab2423813cd0243326b1" kindref="member">print()</a> function or operator <<, which are defined in <code><a href="#rapidxml__print_8hpp" kindref="compound">rapidxml_print.hpp</a></code> header. <pre>using namespace rapidxml;
xml_document<> doc; // character type defaults to char
// ... some code to fill the document
// Print to stream using operator <<
std::cout << doc;
// Print to stream using print function, specifying printing flags
print(std::cout, doc, 0); // 0 means default printing flags
// Print to string using output iterator
std::string s;
print(std::back_inserter(s), doc, 0);
// Print to memory buffer using output iterator
char buffer[4096]; // You are responsible for making the buffer large enough!
char *end = print(buffer, doc, 0); // end contains pointer to character after last printed character
*end = 0; // Add string terminator after XML
</pre></para></sect2></sect1><sect1><h2 id="namespacerapidxml_1differences">3. Differences From Regular XML Parsers</h2><para>RapidXml is an <i>in-situ parser</i>, which allows it to achieve very high parsing speed. In-situ means that parser does not make copies of strings. Instead, it places pointers to the <i>source text</i> in the DOM hierarchy.</para><sect2><h3 id="namespacerapidxml_1lifetime_of_source_text">3.1 Lifetime Of Source Text</h3><para>In-situ parsing requires that source text lives at least as long as the document object. If source text is destroyed, names and values of nodes in DOM tree will become destroyed as well. Additionally, whitespace processing, character entity translation, and zero-termination of strings require that source text be modified during parsing (but see non-destructive mode). This makes the text useless for further processing once it was parsed by RapidXml. <br/><br/>
In many cases however, these are not serious issues.</para></sect2><sect2><h3 id="namespacerapidxml_1ownership_of_strings">3.2 Ownership Of Strings</h3><para>Nodes and attributes produced by RapidXml do not own their name and value strings. They merely hold the pointers to them. This means you have to be careful when setting these values manually, by using <a href="#classrapidxml_1_1xml__base_e099c291e104a0d277307fe71f5e0f9e_1e099c291e104a0d277307fe71f5e0f9e" kindref="member">xml_base::name(const Ch *)</a> or <a href="#classrapidxml_1_1xml__base_18c7469acdca771de9b4f3054053029c_118c7469acdca771de9b4f3054053029c" kindref="member">xml_base::value(const Ch *)</a> functions. Care must be taken to ensure that lifetime of the string passed is at least as long as lifetime of the node/attribute. The easiest way to achieve it is to allocate the string from <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> owned by the document. Use <a href="#classrapidxml_1_1memory__pool_69729185bc59b0875192d667c47b8859_169729185bc59b0875192d667c47b8859" kindref="member">memory_pool::allocate_string()</a> function for this purpose.</para></sect2><sect2><h3 id="namespacerapidxml_1destructive_non_destructive">3.3 Destructive Vs Non-Destructive Mode</h3><para>By default, the parser modifies source text during the parsing process. This is required to achieve character entity translation, whitespace normalization, and zero-termination of strings. <br/><br/>
In some cases this behaviour may be undesirable, for example if source text resides in read only memory, or is mapped to memory directly from file. By using appropriate parser flags (parse_non_destructive), source text modifications can be disabled. However, because RapidXml does in-situ parsing, it obviously has the following side-effects:<ul><li><para>no whitespace normalization is done</para></li><li><para>no entity reference translation is done</para></li><li><para>names and values are not zero-terminated, you must use <a href="#classrapidxml_1_1xml__base_0dae694c8f7e4d89f1003e2f3a15a43c_10dae694c8f7e4d89f1003e2f3a15a43c" kindref="member">xml_base::name_size()</a> and <a href="#classrapidxml_1_1xml__base_aed5ae791b7164c1ee5e649198cbb3db_1aed5ae791b7164c1ee5e649198cbb3db" kindref="member">xml_base::value_size()</a> functions to tell where they end</para></li></ul></para></sect2></sect1><sect1><h2 id="namespacerapidxml_1performance">4. Performance</h2><para>RapidXml achieves its speed through use of several techniques:<ul><li><para>In-situ parsing. When building DOM tree, RapidXml does not make copies of string data, such as node names and values. Instead, it stores pointers to interior of the source text.</para></li><li><para>Use of template metaprogramming techniques. This allows it to move much of the work to compile time. Through magic of the templates, C++ compiler generates a separate copy of parsing code for any combination of parser flags you use. In each copy, all possible decisions are made at compile time and all unused code is omitted.</para></li><li><para>Extensive use of lookup tables for parsing.</para></li><li><para>Hand-tuned C++ with profiling done on several most popular CPUs.</para></li></ul></para><para>This results in a very small and fast code: a parser which is custom tailored to exact needs with each invocation.</para><sect2><h3 id="namespacerapidxml_1performance_charts">4.1 Comparison With Other Parsers</h3><para>The table below compares speed of RapidXml to some other parsers, and to <code>strlen()</code> function executed on the same data. On a modern CPU (as of 2007), you can expect parsing throughput to be close to 1 GB/s. As a rule of thumb, parsing speed is about 50-100x faster than Xerces DOM, 30-60x faster than TinyXml, 3-12x faster than pugxml, and about 5% - 30% faster than pugixml, the fastest XML parser I know of.</para><para><ul><li><para>The test file is a real-world, 50kB large, moderately dense XML file. </para></li><li><para>All timing is done by using RDTSC instruction present in Pentium-compatible CPUs. </para></li><li><para>No profile-guided optimizations are used. </para></li><li><para>All parsers are running in their fastest modes. </para></li><li><para>The results are given in CPU cycles per character, so frequency of CPUs is irrelevant. </para></li><li><para>The results are minimum values from a large number of runs, to minimize effects of operating system activity, task switching, interrupt handling etc. </para></li><li><para>A single parse of the test file takes about 1/10th of a millisecond, so with large number of runs there is a good chance of hitting at least one no-interrupt streak, and obtaining undisturbed results. </para></li></ul><table rows="9" cols="7" border="1" cellpadding="3pt"><tr><th thead="yes"><para><center>Platform</center></para></th><th thead="yes"><para><center>Compiler</center></para></th><th thead="yes"><para>strlen() </para></th><th thead="yes"><para>RapidXml </para></th><th thead="yes"><para>pugixml 0.3 </para></th><th thead="yes"><para>pugxml </para></th><th thead="yes"><para>TinyXml </para></th></tr><tr><td thead="no"><para><center>Pentium 4</center></para></td><td thead="no"><para><center>MSVC 8.0</center></para></td><td thead="no"><para><center>2.5</center></para></td><td thead="no"><para><center>5.4</center></para></td><td thead="no"><para><center>7.0</center></para></td><td thead="no"><para><center>61.7</center></para></td><td thead="no"><para><center>298.8</center></para></td></tr><tr><td thead="no"><para><center>Pentium 4</center></para></td><td thead="no"><para><center>gcc 4.1.1</center></para></td><td thead="no"><para><center>0.8</center></para></td><td thead="no"><para><center>6.1</center></para></td><td thead="no"><para><center>9.5</center></para></td><td thead="no"><para><center>67.0</center></para></td><td thead="no"><para><center>413.2</center></para></td></tr><tr><td thead="no"><para><center>Core 2</center></para></td><td thead="no"><para><center>MSVC 8.0</center></para></td><td thead="no"><para><center>1.0</center></para></td><td thead="no"><para><center>4.5</center></para></td><td thead="no"><para><center>5.0</center></para></td><td thead="no"><para><center>24.6</center></para></td><td thead="no"><para><center>154.8</center></para></td></tr><tr><td thead="no"><para><center>Core 2</center></para></td><td thead="no"><para><center>gcc 4.1.1</center></para></td><td thead="no"><para><center>0.6</center></para></td><td thead="no"><para><center>4.6</center></para></td><td thead="no"><para><center>5.4</center></para></td><td thead="no"><para><center>28.3</center></para></td><td thead="no"><para><center>229.3</center></para></td></tr><tr><td thead="no"><para><center>Athlon XP</center></para></td><td thead="no"><para><center>MSVC 8.0</center></para></td><td thead="no"><para><center>3.1</center></para></td><td thead="no"><para><center>7.7</center></para></td><td thead="no"><para><center>8.0</center></para></td><td thead="no"><para><center>25.5</center></para></td><td thead="no"><para><center>182.6</center></para></td></tr><tr><td thead="no"><para><center>Athlon XP</center></para></td><td thead="no"><para><center>gcc 4.1.1</center></para></td><td thead="no"><para><center>0.9</center></para></td><td thead="no"><para><center>8.2</center></para></td><td thead="no"><para><center>9.2</center></para></td><td thead="no"><para><center>33.7</center></para></td><td thead="no"><para><center>265.2</center></para></td></tr><tr><td thead="no"><para><center>Pentium 3</center></para></td><td thead="no"><para><center>MSVC 8.0</center></para></td><td thead="no"><para><center>2.0</center></para></td><td thead="no"><para><center>6.3</center></para></td><td thead="no"><para><center>7.0</center></para></td><td thead="no"><para><center>30.9</center></para></td><td thead="no"><para><center>211.9</center></para></td></tr><tr><td thead="no"><para><center>Pentium 3</center></para></td><td thead="no"><para><center>gcc 4.1.1</center></para></td><td thead="no"><para><center>1.0</center></para></td><td thead="no"><para><center>6.7</center></para></td><td thead="no"><para><center>8.9</center></para></td><td thead="no"><para><center>35.3</center></para></td><td thead="no"><para><center>316.0</center></para></td></tr></table><i>(*) All results are in CPU cycles per character of source text</i></para></sect2></sect1><sect1><h2 id="namespacerapidxml_1reference">5. Reference</h2><para>This section lists all classes, functions, constants etc. and describes them in detail. </para></sect1></detaileddescription><dl><dt>class
template
<a href="#classrapidxml_1_1memory__pool">rapidxml::memory_pool</a></dt><dt class="indented">
constructor
<a href="#classrapidxml_1_1memory__pool_f8fb3c8f1a564f8045c40bcd07a89866_1f8fb3c8f1a564f8045c40bcd07a89866">memory_pool()</a></dt><dt class="indented">
destructor
<a href="#classrapidxml_1_1memory__pool_6f8c7990d9ec1ed2acf6558b238570eb_16f8c7990d9ec1ed2acf6558b238570eb">~memory_pool()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1memory__pool_750ba3c610b129ac057d817509d08f41_1750ba3c610b129ac057d817509d08f41">allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1memory__pool_462de142669e0ff649e8e615b82bf457_1462de142669e0ff649e8e615b82bf457">allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1memory__pool_69729185bc59b0875192d667c47b8859_169729185bc59b0875192d667c47b8859">allocate_string(const Ch *source=0, std::size_t size=0)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1memory__pool_95c49fcb056e9103ec906a59e3e01d76_195c49fcb056e9103ec906a59e3e01d76">clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1memory__pool_c8bb3912a3ce86b15842e79d0b421204_1c8bb3912a3ce86b15842e79d0b421204">clear()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1memory__pool_c0a55a6ef0837dca67572e357100d78a_1c0a55a6ef0837dca67572e357100d78a">set_allocator(alloc_func *af, free_func *ff)</a></dt><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><p/><p/><dt>class <a href="#classrapidxml_1_1parse__error">rapidxml::parse_error</a></dt><dt class="indented">
constructor
<a href="#classrapidxml_1_1parse__error_4dd8d1bdbd9221df4dcb90cafaee3332_14dd8d1bdbd9221df4dcb90cafaee3332">parse_error(const char *what, void *where)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1parse__error_ff06f49065b54a8a86e02e9a2441a8ba_1ff06f49065b54a8a86e02e9a2441a8ba">what() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1parse__error_377be7d201d95221c318682c35377aca_1377be7d201d95221c318682c35377aca">where() const </a></dt><dt class="indented"/><dt class="indented"/><p/><dt>class
template
<a href="#classrapidxml_1_1xml__attribute">rapidxml::xml_attribute</a></dt><dt class="indented">
constructor
<a href="#classrapidxml_1_1xml__attribute_d5464aadf08269a886b730993525db34_1d5464aadf08269a886b730993525db34">xml_attribute()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__attribute_77aea7d8d996ba4f6bd61cc478a4e72d_177aea7d8d996ba4f6bd61cc478a4e72d">document() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__attribute_5c4a98d2b75f9b41b12c110108fd55ab_15c4a98d2b75f9b41b12c110108fd55ab">previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__attribute_1b8a814d0d3a7165396b08433eee8a91_11b8a814d0d3a7165396b08433eee8a91">next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented"/><dt class="indented"/><dt class="indented"/><p/><dt>class
template
<a href="#classrapidxml_1_1xml__base">rapidxml::xml_base</a></dt><dt class="indented">
constructor
<a href="#classrapidxml_1_1xml__base_23630d2c130a9e0e3f3afa7584a9b218_123630d2c130a9e0e3f3afa7584a9b218">xml_base()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_622eade29fdf7806d3ef93ac4d90e707_1622eade29fdf7806d3ef93ac4d90e707">name() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_0dae694c8f7e4d89f1003e2f3a15a43c_10dae694c8f7e4d89f1003e2f3a15a43c">name_size() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_c54fa4987fb503916a7b541eb15c9c7f_1c54fa4987fb503916a7b541eb15c9c7f">value() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_aed5ae791b7164c1ee5e649198cbb3db_1aed5ae791b7164c1ee5e649198cbb3db">value_size() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_4e7e23d06d48126c65b1f6266acfba5c_14e7e23d06d48126c65b1f6266acfba5c">name(const Ch *name, std::size_t size)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_e099c291e104a0d277307fe71f5e0f9e_1e099c291e104a0d277307fe71f5e0f9e">name(const Ch *name)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_d9640aa3f5374673cb72a5289b6c91eb_1d9640aa3f5374673cb72a5289b6c91eb">value(const Ch *value, std::size_t size)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_18c7469acdca771de9b4f3054053029c_118c7469acdca771de9b4f3054053029c">value(const Ch *value)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__base_798e8df7ea53ade4d9f0701017dce80e_1798e8df7ea53ade4d9f0701017dce80e">parent() const </a></dt><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><p/><dt>class
template
<a href="#classrapidxml_1_1xml__document">rapidxml::xml_document</a></dt><dt class="indented">
constructor
<a href="#classrapidxml_1_1xml__document_6ce266cc52d549c42abe3a3d5e8af9ba_16ce266cc52d549c42abe3a3d5e8af9ba">xml_document()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c">parse(Ch *text)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__document_c8bb3912a3ce86b15842e79d0b421204_1c8bb3912a3ce86b15842e79d0b421204">clear()</a></dt><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><p/><p/><p/><p/><p/><p/><p/><p/><p/><dt>class
template
<a href="#classrapidxml_1_1xml__node">rapidxml::xml_node</a></dt><dt class="indented">
constructor
<a href="#classrapidxml_1_1xml__node_34c55af3504549a475e5b9dfcaa6adf5_134c55af3504549a475e5b9dfcaa6adf5">xml_node(node_type type)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_975e86937621ae4afe6a423219de30d0_1975e86937621ae4afe6a423219de30d0">type() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_77aea7d8d996ba4f6bd61cc478a4e72d_177aea7d8d996ba4f6bd61cc478a4e72d">document() const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_7823e36687669e59c2afdf66334ef35a_17823e36687669e59c2afdf66334ef35a">first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_fcb6e2209b591a36d2dadba20d2bc7cc_1fcb6e2209b591a36d2dadba20d2bc7cc">last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_ac2f6886c0107e9d5f156e9542546df6_1ac2f6886c0107e9d5f156e9542546df6">previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_b3ead2cefecc03a813836203e3f6f38f_1b3ead2cefecc03a813836203e3f6f38f">next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_5810a09f82f8d53efbe9456286dcec83_15810a09f82f8d53efbe9456286dcec83">first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_16953d66751b5b949ee4ee2d9c0bc63a_116953d66751b5b949ee4ee2d9c0bc63a">last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const </a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_a78759bfa429fa2ab6bc5fe617cfa3cf_1a78759bfa429fa2ab6bc5fe617cfa3cf">type(node_type type)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_0c39df6617e709eb2fba11300dea63f2_10c39df6617e709eb2fba11300dea63f2">prepend_node(xml_node< Ch > *child)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_86de2e22276826089b7baed2599f8dee_186de2e22276826089b7baed2599f8dee">append_node(xml_node< Ch > *child)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_780972a57fc447250ab47cc8f421b65e_1780972a57fc447250ab47cc8f421b65e">insert_node(xml_node< Ch > *where, xml_node< Ch > *child)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_9a31d861e1bddc710839c551a5d2b3a4_19a31d861e1bddc710839c551a5d2b3a4">remove_first_node()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_87addf2bc127ee31aa4b5295d3c9b530_187addf2bc127ee31aa4b5295d3c9b530">remove_last_node()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_9316463a2201631e7e2062b17729f9cd_19316463a2201631e7e2062b17729f9cd">remove_node(xml_node< Ch > *where)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_0218147d13e41d5fa60ced4e7a7e9726_10218147d13e41d5fa60ced4e7a7e9726">remove_all_nodes()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_f6dffa513da74cc0be71a7ba84f8265e_1f6dffa513da74cc0be71a7ba84f8265e">prepend_attribute(xml_attribute< Ch > *attribute)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_8fbd4f5ef7169d493da9f8d87ac04b77_18fbd4f5ef7169d493da9f8d87ac04b77">append_attribute(xml_attribute< Ch > *attribute)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_070d5888b0557fe06a5b24961de1b988_1070d5888b0557fe06a5b24961de1b988">insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_4eea4a7f6cb484ca9944f7eafe6e1843_14eea4a7f6cb484ca9944f7eafe6e1843">remove_first_attribute()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_37d87c4d5d89fa0cf05b72ee8d4cba3b_137d87c4d5d89fa0cf05b72ee8d4cba3b">remove_last_attribute()</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_c75154db2e768c0e5b541fc8cd0775ab_1c75154db2e768c0e5b541fc8cd0775ab">remove_attribute(xml_attribute< Ch > *where)</a></dt><dt class="indented">function <a href="#classrapidxml_1_1xml__node_59e6ad4cfd5e8096c052e71d79561eda_159e6ad4cfd5e8096c052e71d79561eda">remove_all_attributes()</a></dt><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><p/><dt>namespace <a href="#namespacerapidxml">rapidxml</a></dt><dt class="indented">enum <a href="#namespacerapidxml_6a276b85e2da28c5f9c3dbce61c55682_16a276b85e2da28c5f9c3dbce61c55682">node_type</a></dt><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented"/><dt class="indented">function <a href="#namespacerapidxml_ff5d67f74437199d316d2b2660653ae1_1ff5d67f74437199d316d2b2660653ae1">parse_error_handler(const char *what, void *where)</a></dt><dt class="indented">function <a href="#namespacerapidxml_b94d570fc4c4ab2423813cd0243326b1_1b94d570fc4c4ab2423813cd0243326b1">print(OutIt out, const xml_node< Ch > &node, int flags=0)</a></dt><dt class="indented">function <a href="#namespacerapidxml_13bc37d6d1047acb0efdbc1689221a5e_113bc37d6d1047acb0efdbc1689221a5e">print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0)</a></dt><dt class="indented">function <a href="#namespacerapidxml_5619b38000d967fb223b2b0a8c17463a_15619b38000d967fb223b2b0a8c17463a">operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node)</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_87e8bbab53702cf3b438bd553c10b6b9_187e8bbab53702cf3b438bd553c10b6b9">parse_no_data_nodes</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_97e2c4fdc04fae17126f9971a4fc993e_197e2c4fdc04fae17126f9971a4fc993e">parse_no_element_values</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_9cae3801e70437cbc410c24bf6be691c_19cae3801e70437cbc410c24bf6be691c">parse_no_string_terminators</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_7223b7815c4fb8b42e6e4e77e1ea6b97_17223b7815c4fb8b42e6e4e77e1ea6b97">parse_no_entity_translation</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_ccde57f6054857ee4042a1b4d98c83b9_1ccde57f6054857ee4042a1b4d98c83b9">parse_no_utf8</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_52e2c934ad9c845a5f4cc49570470556_152e2c934ad9c845a5f4cc49570470556">parse_declaration_node</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_0f7479dacbc868456d07897a8c072784_10f7479dacbc868456d07897a8c072784">parse_comment_nodes</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_8e187746ba1ca04f107951ad32df962e_18e187746ba1ca04f107951ad32df962e">parse_doctype_node</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_1c20b2b2b75711cd76423e119c49f830_11c20b2b2b75711cd76423e119c49f830">parse_pi_nodes</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_a5daff9d61c7d4eaf98e4d42efe628ee_1a5daff9d61c7d4eaf98e4d42efe628ee">parse_validate_closing_tags</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_ac1f06b1afd47b812732fb521b146fd9_1ac1f06b1afd47b812732fb521b146fd9">parse_trim_whitespace</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_88f95d4e275ba01408fefde83078651b_188f95d4e275ba01408fefde83078651b">parse_normalize_whitespace</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_45751cf2f38fd6915f35b3122b46d5b6_145751cf2f38fd6915f35b3122b46d5b6">parse_default</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_a97ba1a0a79a6d66f4eef3612508d943_1a97ba1a0a79a6d66f4eef3612508d943">parse_non_destructive</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_398c5476e76102f8bd76c10bb0abbe10_1398c5476e76102f8bd76c10bb0abbe10">parse_fastest</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_b4f2515265facb42291570307924bd57_1b4f2515265facb42291570307924bd57">parse_full</a></dt><dt class="indented">
constant
<a href="#namespacerapidxml_b08b8d4293c203b69ed6c5ae77ac1907_1b08b8d4293c203b69ed6c5ae77ac1907">print_no_indenting</a></dt><p/><p/><p/><p/></dl><hr/><h3 class="reference-header" id="classrapidxml_1_1memory__pool">class
template
rapidxml::memory_pool</h3>
Defined in <a href="rapidxml.hpp">rapidxml.hpp</a><br/>
Base class for
<a href="#classrapidxml_1_1xml__document">xml_document</a> <h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">This class is used by the parser to create new nodes and attributes, without overheads of dynamic memory allocation. In most cases, you will not need to use this class directly. However, if you need to create nodes manually or modify names/values of nodes, you are encouraged to use <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> of relevant <a href="#classrapidxml_1_1xml__document" kindref="compound">xml_document</a> to allocate the memory. Not only is this faster than allocating them by using <code>new</code> operator, but also their lifetime will be tied to the lifetime of document, possibly simplyfing memory management. <br/><br/>
Call <a href="#classrapidxml_1_1memory__pool_750ba3c610b129ac057d817509d08f41_1750ba3c610b129ac057d817509d08f41" kindref="member">allocate_node()</a> or <a href="#classrapidxml_1_1memory__pool_462de142669e0ff649e8e615b82bf457_1462de142669e0ff649e8e615b82bf457" kindref="member">allocate_attribute()</a> functions to obtain new nodes or attributes from the pool. You can also call <a href="#classrapidxml_1_1memory__pool_69729185bc59b0875192d667c47b8859_169729185bc59b0875192d667c47b8859" kindref="member">allocate_string()</a> function to allocate strings. Such strings can then be used as names or values of nodes without worrying about their lifetime. Note that there is no <code>free()</code> function -- all allocations are freed at once when <a href="#classrapidxml_1_1memory__pool_c8bb3912a3ce86b15842e79d0b421204_1c8bb3912a3ce86b15842e79d0b421204" kindref="member">clear()</a> function is called, or when the pool is destroyed. <br/><br/>
It is also possible to create a standalone <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a>, and use it to allocate nodes, whose lifetime will not be tied to any document. <br/><br/>
Pool maintains <code>RAPIDXML_STATIC_POOL_SIZE</code> bytes of statically allocated memory. Until static memory is exhausted, no dynamic memory allocations are done. When static memory is exhausted, pool allocates additional blocks of memory of size <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> each, by using global <code>new[]</code> and <code>delete[]</code> operators. This behaviour can be changed by setting custom allocation routines. Use <a href="#classrapidxml_1_1memory__pool_c0a55a6ef0837dca67572e357100d78a_1c0a55a6ef0837dca67572e357100d78a" kindref="member">set_allocator()</a> function to set them. <br/><br/>
Allocations for nodes, attributes and strings are aligned at <code>RAPIDXML_ALIGNMENT</code> bytes. This value defaults to the size of pointer on target architecture. <br/><br/>
To obtain absolutely top performance from the parser, it is important that all nodes are allocated from a single, contiguous block of memory. Otherwise, cache misses when jumping between two (or more) disjoint blocks of memory can slow down parsing quite considerably. If required, you can tweak <code>RAPIDXML_STATIC_POOL_SIZE</code>, <code>RAPIDXML_DYNAMIC_POOL_SIZE</code> and <code>RAPIDXML_ALIGNMENT</code> to obtain best wasted memory to performance compromise. To do it, define their values before <a href="#rapidxml_8hpp" kindref="compound">rapidxml.hpp</a> file is included. </para><h4>Parameters</h4><dl><dt class="parameter-name">Ch</dt><dd>Character type of created nodes. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_f8fb3c8f1a564f8045c40bcd07a89866_1f8fb3c8f1a564f8045c40bcd07a89866">
constructor
memory_pool::memory_pool</h3><h4>Synopsis</h4><code class="synopsis">memory_pool();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Constructs empty pool with default allocator functions. </para><p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_6f8c7990d9ec1ed2acf6558b238570eb_16f8c7990d9ec1ed2acf6558b238570eb">
destructor
memory_pool::~memory_pool</h3><h4>Synopsis</h4><code class="synopsis">~memory_pool();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Destroys pool and frees all the memory. This causes memory occupied by nodes allocated by the pool to be freed. Nodes allocated from the pool are no longer valid. </para><p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_750ba3c610b129ac057d817509d08f41_1750ba3c610b129ac057d817509d08f41">function memory_pool::allocate_node</h3><h4>Synopsis</h4><code class="synopsis">xml_node<Ch>* allocate_node(node_type type, const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Allocates a new node from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call <a href="#namespacerapidxml_ff5d67f74437199d316d2b2660653ae1_1ff5d67f74437199d316d2b2660653ae1" kindref="member">rapidxml::parse_error_handler()</a> function. </para><h4>Parameters</h4><dl><dt class="parameter-name">type</dt><dd class="parameter-def">Type of node to create. </dd></dl><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name to assign to the node, or 0 to assign no name. </dd></dl><dl><dt class="parameter-name">value</dt><dd class="parameter-def">Value to assign to the node, or 0 to assign no value. </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name to assign, or 0 to automatically calculate size from name string. </dd></dl><dl><dt class="parameter-name">value_size</dt><dd class="parameter-def">Size of value to assign, or 0 to automatically calculate size from value string. </dd></dl><h4>Returns</h4>Pointer to allocated node. This pointer will never be NULL. <p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_462de142669e0ff649e8e615b82bf457_1462de142669e0ff649e8e615b82bf457">function memory_pool::allocate_attribute</h3><h4>Synopsis</h4><code class="synopsis">xml_attribute<Ch>* allocate_attribute(const Ch *name=0, const Ch *value=0, std::size_t name_size=0, std::size_t value_size=0);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Allocates a new attribute from the pool, and optionally assigns name and value to it. If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call <a href="#namespacerapidxml_ff5d67f74437199d316d2b2660653ae1_1ff5d67f74437199d316d2b2660653ae1" kindref="member">rapidxml::parse_error_handler()</a> function. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name to assign to the attribute, or 0 to assign no name. </dd></dl><dl><dt class="parameter-name">value</dt><dd class="parameter-def">Value to assign to the attribute, or 0 to assign no value. </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name to assign, or 0 to automatically calculate size from name string. </dd></dl><dl><dt class="parameter-name">value_size</dt><dd class="parameter-def">Size of value to assign, or 0 to automatically calculate size from value string. </dd></dl><h4>Returns</h4>Pointer to allocated attribute. This pointer will never be NULL. <p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_69729185bc59b0875192d667c47b8859_169729185bc59b0875192d667c47b8859">function memory_pool::allocate_string</h3><h4>Synopsis</h4><code class="synopsis">Ch* allocate_string(const Ch *source=0, std::size_t size=0);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Allocates a char array of given size from the pool, and optionally copies a given string to it. If the allocation request cannot be accomodated, this function will throw <code>std::bad_alloc</code>. If exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function will call <a href="#namespacerapidxml_ff5d67f74437199d316d2b2660653ae1_1ff5d67f74437199d316d2b2660653ae1" kindref="member">rapidxml::parse_error_handler()</a> function. </para><h4>Parameters</h4><dl><dt class="parameter-name">source</dt><dd class="parameter-def">String to initialize the allocated memory with, or 0 to not initialize it. </dd></dl><dl><dt class="parameter-name">size</dt><dd class="parameter-def">Number of characters to allocate, or zero to calculate it automatically from source string length; if size is 0, source string must be specified and null terminated. </dd></dl><h4>Returns</h4>Pointer to allocated char array. This pointer will never be NULL. <p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_95c49fcb056e9103ec906a59e3e01d76_195c49fcb056e9103ec906a59e3e01d76">function memory_pool::clone_node</h3><h4>Synopsis</h4><code class="synopsis">xml_node<Ch>* clone_node(const xml_node< Ch > *source, xml_node< Ch > *result=0);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Clones an <a href="#classrapidxml_1_1xml__node" kindref="compound">xml_node</a> and its hierarchy of child nodes and attributes. Nodes and attributes are allocated from this memory pool. Names and values are not cloned, they are shared between the clone and the source. Result node can be optionally specified as a second parameter, in which case its contents will be replaced with cloned source node. This is useful when you want to clone entire document. </para><h4>Parameters</h4><dl><dt class="parameter-name">source</dt><dd class="parameter-def">Node to clone. </dd></dl><dl><dt class="parameter-name">result</dt><dd class="parameter-def">Node to put results in, or 0 to automatically allocate result node </dd></dl><h4>Returns</h4>Pointer to cloned node. This pointer will never be NULL. <p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_c8bb3912a3ce86b15842e79d0b421204_1c8bb3912a3ce86b15842e79d0b421204">function memory_pool::clear</h3><h4>Synopsis</h4><code class="synopsis">void clear();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Clears the pool. This causes memory occupied by nodes allocated by the pool to be freed. Any nodes or strings allocated from the pool will no longer be valid. </para><p/><h3 class="reference-header" id="classrapidxml_1_1memory__pool_c0a55a6ef0837dca67572e357100d78a_1c0a55a6ef0837dca67572e357100d78a">function memory_pool::set_allocator</h3><h4>Synopsis</h4><code class="synopsis">void set_allocator(alloc_func *af, free_func *ff);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Sets or resets the user-defined memory allocation functions for the pool. This can only be called when no memory is allocated from the pool yet, otherwise results are undefined. Allocation function must not return invalid pointer on failure. It should either throw, stop the program, or use <code>longjmp()</code> function to pass control to other place of program. If it returns invalid pointer, results are undefined. <br/><br/>
User defined allocation functions must have the following forms: <br/><code><br/>
void *allocate(std::size_t size); <br/>
void free(void *pointer); </code><br/></para><h4>Parameters</h4><dl><dt class="parameter-name">af</dt><dd class="parameter-def">Allocation function, or 0 to restore default function </dd></dl><dl><dt class="parameter-name">ff</dt><dd class="parameter-def">Free function, or 0 to restore default function </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1parse__error">class rapidxml::parse_error</h3>
Defined in <a href="rapidxml.hpp">rapidxml.hpp</a><br/><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse error exception. This exception is thrown by the parser when an error occurs. Use <a href="#classrapidxml_1_1parse__error_ff06f49065b54a8a86e02e9a2441a8ba_1ff06f49065b54a8a86e02e9a2441a8ba" kindref="member">what()</a> function to get human-readable error message. Use <a href="#classrapidxml_1_1parse__error_377be7d201d95221c318682c35377aca_1377be7d201d95221c318682c35377aca" kindref="member">where()</a> function to get a pointer to position within source text where error was detected. <br/><br/>
If throwing exceptions by the parser is undesirable, it can be disabled by defining RAPIDXML_NO_EXCEPTIONS macro before <a href="#rapidxml_8hpp" kindref="compound">rapidxml.hpp</a> is included. This will cause the parser to call <a href="#namespacerapidxml_ff5d67f74437199d316d2b2660653ae1_1ff5d67f74437199d316d2b2660653ae1" kindref="member">rapidxml::parse_error_handler()</a> function instead of throwing an exception. This function must be defined by the user. <br/><br/>
This class derives from <code>std::exception</code> class. </para><p/><h3 class="reference-header" id="classrapidxml_1_1parse__error_4dd8d1bdbd9221df4dcb90cafaee3332_14dd8d1bdbd9221df4dcb90cafaee3332">
constructor
parse_error::parse_error</h3><h4>Synopsis</h4><code class="synopsis">parse_error(const char *what, void *where);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Constructs parse error. </para><p/><h3 class="reference-header" id="classrapidxml_1_1parse__error_ff06f49065b54a8a86e02e9a2441a8ba_1ff06f49065b54a8a86e02e9a2441a8ba">function parse_error::what</h3><h4>Synopsis</h4><code class="synopsis">virtual const char* what() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets human readable description of error. </para><h4>Returns</h4>Pointer to null terminated description of the error. <p/><h3 class="reference-header" id="classrapidxml_1_1parse__error_377be7d201d95221c318682c35377aca_1377be7d201d95221c318682c35377aca">function parse_error::where</h3><h4>Synopsis</h4><code class="synopsis">Ch* where() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets pointer to character data where error happened. Ch should be the same as char type of <a href="#classrapidxml_1_1xml__document" kindref="compound">xml_document</a> that produced the error. </para><h4>Returns</h4>Pointer to location within the parsed string where error occured. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__attribute">class
template
rapidxml::xml_attribute</h3>
Defined in <a href="rapidxml.hpp">rapidxml.hpp</a><br/>
Inherits from
<a href="#classrapidxml_1_1xml__base">xml_base</a> <br/><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Class representing attribute node of XML document. Each attribute has name and value strings, which are available through <a href="#classrapidxml_1_1xml__base_622eade29fdf7806d3ef93ac4d90e707_1622eade29fdf7806d3ef93ac4d90e707" kindref="member">name()</a> and <a href="#classrapidxml_1_1xml__base_c54fa4987fb503916a7b541eb15c9c7f_1c54fa4987fb503916a7b541eb15c9c7f" kindref="member">value()</a> functions (inherited from <a href="#classrapidxml_1_1xml__base" kindref="compound">xml_base</a>). Note that after parse, both name and value of attribute will point to interior of source text used for parsing. Thus, this text must persist in memory for the lifetime of attribute. </para><h4>Parameters</h4><dl><dt class="parameter-name">Ch</dt><dd>Character type to use. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__attribute_d5464aadf08269a886b730993525db34_1d5464aadf08269a886b730993525db34">
constructor
xml_attribute::xml_attribute</h3><h4>Synopsis</h4><code class="synopsis">xml_attribute();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Constructs an empty attribute with the specified type. Consider using <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> of appropriate <a href="#classrapidxml_1_1xml__document" kindref="compound">xml_document</a> if allocating attributes manually. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__attribute_77aea7d8d996ba4f6bd61cc478a4e72d_177aea7d8d996ba4f6bd61cc478a4e72d">function xml_attribute::document</h3><h4>Synopsis</h4><code class="synopsis">xml_document<Ch>* document() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets document of which attribute is a child. </para><h4>Returns</h4>Pointer to document that contains this attribute, or 0 if there is no parent document. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__attribute_5c4a98d2b75f9b41b12c110108fd55ab_15c4a98d2b75f9b41b12c110108fd55ab">function xml_attribute::previous_attribute</h3><h4>Synopsis</h4><code class="synopsis">xml_attribute<Ch>* previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets previous attribute, optionally matching attribute name. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found attribute, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__attribute_1b8a814d0d3a7165396b08433eee8a91_11b8a814d0d3a7165396b08433eee8a91">function xml_attribute::next_attribute</h3><h4>Synopsis</h4><code class="synopsis">xml_attribute<Ch>* next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets next attribute, optionally matching attribute name. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found attribute, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__base">class
template
rapidxml::xml_base</h3>
Defined in <a href="rapidxml.hpp">rapidxml.hpp</a><br/>
Base class for
<a href="#classrapidxml_1_1xml__attribute">xml_attribute</a> <a href="#classrapidxml_1_1xml__node">xml_node</a> <h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Base class for <a href="#classrapidxml_1_1xml__node" kindref="compound">xml_node</a> and <a href="#classrapidxml_1_1xml__attribute" kindref="compound">xml_attribute</a> implementing common functions: <a href="#classrapidxml_1_1xml__base_622eade29fdf7806d3ef93ac4d90e707_1622eade29fdf7806d3ef93ac4d90e707" kindref="member">name()</a>, <a href="#classrapidxml_1_1xml__base_0dae694c8f7e4d89f1003e2f3a15a43c_10dae694c8f7e4d89f1003e2f3a15a43c" kindref="member">name_size()</a>, <a href="#classrapidxml_1_1xml__base_c54fa4987fb503916a7b541eb15c9c7f_1c54fa4987fb503916a7b541eb15c9c7f" kindref="member">value()</a>, <a href="#classrapidxml_1_1xml__base_aed5ae791b7164c1ee5e649198cbb3db_1aed5ae791b7164c1ee5e649198cbb3db" kindref="member">value_size()</a> and <a href="#classrapidxml_1_1xml__base_798e8df7ea53ade4d9f0701017dce80e_1798e8df7ea53ade4d9f0701017dce80e" kindref="member">parent()</a>. </para><h4>Parameters</h4><dl><dt class="parameter-name">Ch</dt><dd>Character type to use </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_23630d2c130a9e0e3f3afa7584a9b218_123630d2c130a9e0e3f3afa7584a9b218">
constructor
xml_base::xml_base</h3><h4>Synopsis</h4><code class="synopsis">xml_base();
</code><p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_622eade29fdf7806d3ef93ac4d90e707_1622eade29fdf7806d3ef93ac4d90e707">function xml_base::name</h3><h4>Synopsis</h4><code class="synopsis">Ch* name() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets name of the node. Interpretation of name depends on type of node. Note that name will not be zero-terminated if <a href="#namespacerapidxml_9cae3801e70437cbc410c24bf6be691c_19cae3801e70437cbc410c24bf6be691c" kindref="member">rapidxml::parse_no_string_terminators</a> option was selected during parse. <br/><br/>
Use <a href="#classrapidxml_1_1xml__base_0dae694c8f7e4d89f1003e2f3a15a43c_10dae694c8f7e4d89f1003e2f3a15a43c" kindref="member">name_size()</a> function to determine length of the name. </para><h4>Returns</h4>Name of node, or empty string if node has no name. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_0dae694c8f7e4d89f1003e2f3a15a43c_10dae694c8f7e4d89f1003e2f3a15a43c">function xml_base::name_size</h3><h4>Synopsis</h4><code class="synopsis">std::size_t name_size() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets size of node name, not including terminator character. This function works correctly irrespective of whether name is or is not zero terminated. </para><h4>Returns</h4>Size of node name, in characters. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_c54fa4987fb503916a7b541eb15c9c7f_1c54fa4987fb503916a7b541eb15c9c7f">function xml_base::value</h3><h4>Synopsis</h4><code class="synopsis">Ch* value() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets value of node. Interpretation of value depends on type of node. Note that value will not be zero-terminated if <a href="#namespacerapidxml_9cae3801e70437cbc410c24bf6be691c_19cae3801e70437cbc410c24bf6be691c" kindref="member">rapidxml::parse_no_string_terminators</a> option was selected during parse. <br/><br/>
Use <a href="#classrapidxml_1_1xml__base_aed5ae791b7164c1ee5e649198cbb3db_1aed5ae791b7164c1ee5e649198cbb3db" kindref="member">value_size()</a> function to determine length of the value. </para><h4>Returns</h4>Value of node, or empty string if node has no value. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_aed5ae791b7164c1ee5e649198cbb3db_1aed5ae791b7164c1ee5e649198cbb3db">function xml_base::value_size</h3><h4>Synopsis</h4><code class="synopsis">std::size_t value_size() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets size of node value, not including terminator character. This function works correctly irrespective of whether value is or is not zero terminated. </para><h4>Returns</h4>Size of node value, in characters. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_4e7e23d06d48126c65b1f6266acfba5c_14e7e23d06d48126c65b1f6266acfba5c">function xml_base::name</h3><h4>Synopsis</h4><code class="synopsis">void name(const Ch *name, std::size_t size);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Sets name of node to a non zero-terminated string. See <a href="#namespacerapidxml_1ownership_of_strings" kindref="member">Ownership Of Strings</a> . <br/><br/>
Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> of the document to allocate the string - on destruction of the document the string will be automatically freed. <br/><br/>
Size of name must be specified separately, because name does not have to be zero terminated. Use <a href="#classrapidxml_1_1xml__base_e099c291e104a0d277307fe71f5e0f9e_1e099c291e104a0d277307fe71f5e0f9e" kindref="member">name(const Ch *)</a> function to have the length automatically calculated (string must be zero terminated). </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of node to set. Does not have to be zero terminated. </dd></dl><dl><dt class="parameter-name">size</dt><dd class="parameter-def">Size of name, in characters. This does not include zero terminator, if one is present. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_e099c291e104a0d277307fe71f5e0f9e_1e099c291e104a0d277307fe71f5e0f9e">function xml_base::name</h3><h4>Synopsis</h4><code class="synopsis">void name(const Ch *name);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Sets name of node to a zero-terminated string. See also <a href="#namespacerapidxml_1ownership_of_strings" kindref="member">Ownership Of Strings</a> and <a href="#classrapidxml_1_1xml__base_4e7e23d06d48126c65b1f6266acfba5c_14e7e23d06d48126c65b1f6266acfba5c" kindref="member">xml_node::name(const Ch *, std::size_t)</a>. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of node to set. Must be zero terminated. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_d9640aa3f5374673cb72a5289b6c91eb_1d9640aa3f5374673cb72a5289b6c91eb">function xml_base::value</h3><h4>Synopsis</h4><code class="synopsis">void value(const Ch *value, std::size_t size);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Sets value of node to a non zero-terminated string. See <a href="#namespacerapidxml_1ownership_of_strings" kindref="member">Ownership Of Strings</a> . <br/><br/>
Note that node does not own its name or value, it only stores a pointer to it. It will not delete or otherwise free the pointer on destruction. It is reponsibility of the user to properly manage lifetime of the string. The easiest way to achieve it is to use <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> of the document to allocate the string - on destruction of the document the string will be automatically freed. <br/><br/>
Size of value must be specified separately, because it does not have to be zero terminated. Use <a href="#classrapidxml_1_1xml__base_18c7469acdca771de9b4f3054053029c_118c7469acdca771de9b4f3054053029c" kindref="member">value(const Ch *)</a> function to have the length automatically calculated (string must be zero terminated). <br/><br/>
If an element has a child node of type node_data, it will take precedence over element value when printing. If you want to manipulate data of elements using values, use parser flag <a href="#namespacerapidxml_87e8bbab53702cf3b438bd553c10b6b9_187e8bbab53702cf3b438bd553c10b6b9" kindref="member">rapidxml::parse_no_data_nodes</a> to prevent creation of data nodes by the parser. </para><h4>Parameters</h4><dl><dt class="parameter-name">value</dt><dd class="parameter-def">value of node to set. Does not have to be zero terminated. </dd></dl><dl><dt class="parameter-name">size</dt><dd class="parameter-def">Size of value, in characters. This does not include zero terminator, if one is present. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_18c7469acdca771de9b4f3054053029c_118c7469acdca771de9b4f3054053029c">function xml_base::value</h3><h4>Synopsis</h4><code class="synopsis">void value(const Ch *value);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Sets value of node to a zero-terminated string. See also <a href="#namespacerapidxml_1ownership_of_strings" kindref="member">Ownership Of Strings</a> and <a href="#classrapidxml_1_1xml__base_d9640aa3f5374673cb72a5289b6c91eb_1d9640aa3f5374673cb72a5289b6c91eb" kindref="member">xml_node::value(const Ch *, std::size_t)</a>. </para><h4>Parameters</h4><dl><dt class="parameter-name">value</dt><dd class="parameter-def">Vame of node to set. Must be zero terminated. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__base_798e8df7ea53ade4d9f0701017dce80e_1798e8df7ea53ade4d9f0701017dce80e">function xml_base::parent</h3><h4>Synopsis</h4><code class="synopsis">xml_node<Ch>* parent() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets node parent. </para><h4>Returns</h4>Pointer to parent node, or 0 if there is no parent. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__document">class
template
rapidxml::xml_document</h3>
Defined in <a href="rapidxml.hpp">rapidxml.hpp</a><br/>
Inherits from
<a href="#classrapidxml_1_1xml__node">xml_node</a> <a href="#classrapidxml_1_1memory__pool">memory_pool</a> <br/><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">This class represents root of the DOM hierarchy. It is also an <a href="#classrapidxml_1_1xml__node" kindref="compound">xml_node</a> and a <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> through public inheritance. Use <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">parse()</a> function to build a DOM tree from a zero-terminated XML text string. <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">parse()</a> function allocates memory for nodes and attributes by using functions of <a href="#classrapidxml_1_1xml__document" kindref="compound">xml_document</a>, which are inherited from <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a>. To access root node of the document, use the document itself, as if it was an <a href="#classrapidxml_1_1xml__node" kindref="compound">xml_node</a>. </para><h4>Parameters</h4><dl><dt class="parameter-name">Ch</dt><dd>Character type to use. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__document_6ce266cc52d549c42abe3a3d5e8af9ba_16ce266cc52d549c42abe3a3d5e8af9ba">
constructor
xml_document::xml_document</h3><h4>Synopsis</h4><code class="synopsis">xml_document();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Constructs empty XML document. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c">function xml_document::parse</h3><h4>Synopsis</h4><code class="synopsis">void parse(Ch *text);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parses zero-terminated XML string according to given flags. Passed string will be modified by the parser, unless <a href="#namespacerapidxml_a97ba1a0a79a6d66f4eef3612508d943_1a97ba1a0a79a6d66f4eef3612508d943" kindref="member">rapidxml::parse_non_destructive</a> flag is used. The string must persist for the lifetime of the document. In case of error, <a href="#classrapidxml_1_1parse__error" kindref="compound">rapidxml::parse_error</a> exception will be thrown. <br/><br/>
If you want to parse contents of a file, you must first load the file into the memory, and pass pointer to its beginning. Make sure that data is zero-terminated. <br/><br/>
Document can be parsed into multiple times. Each new call to parse removes previous nodes and attributes (if any), but does not clear memory pool. </para><h4>Parameters</h4><dl><dt class="parameter-name">text</dt><dd class="parameter-def">XML data to parse; pointer is non-const to denote fact that this data may be modified by the parser. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__document_c8bb3912a3ce86b15842e79d0b421204_1c8bb3912a3ce86b15842e79d0b421204">function xml_document::clear</h3><h4>Synopsis</h4><code class="synopsis">void clear();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Clears the document by deleting all nodes and clearing the memory pool. All nodes owned by document pool are destroyed. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node">class
template
rapidxml::xml_node</h3>
Defined in <a href="rapidxml.hpp">rapidxml.hpp</a><br/>
Inherits from
<a href="#classrapidxml_1_1xml__base">xml_base</a> <br/>
Base class for
<a href="#classrapidxml_1_1xml__document">xml_document</a> <h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Class representing a node of XML document. Each node may have associated name and value strings, which are available through <a href="#classrapidxml_1_1xml__base_622eade29fdf7806d3ef93ac4d90e707_1622eade29fdf7806d3ef93ac4d90e707" kindref="member">name()</a> and <a href="#classrapidxml_1_1xml__base_c54fa4987fb503916a7b541eb15c9c7f_1c54fa4987fb503916a7b541eb15c9c7f" kindref="member">value()</a> functions. Interpretation of name and value depends on type of the node. Type of node can be determined by using <a href="#classrapidxml_1_1xml__node_975e86937621ae4afe6a423219de30d0_1975e86937621ae4afe6a423219de30d0" kindref="member">type()</a> function. <br/><br/>
Note that after parse, both name and value of node, if any, will point interior of source text used for parsing. Thus, this text must persist in the memory for the lifetime of node. </para><h4>Parameters</h4><dl><dt class="parameter-name">Ch</dt><dd>Character type to use. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_34c55af3504549a475e5b9dfcaa6adf5_134c55af3504549a475e5b9dfcaa6adf5">
constructor
xml_node::xml_node</h3><h4>Synopsis</h4><code class="synopsis">xml_node(node_type type);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Constructs an empty node with the specified type. Consider using <a href="#classrapidxml_1_1memory__pool" kindref="compound">memory_pool</a> of appropriate document to allocate nodes manually. </para><h4>Parameters</h4><dl><dt class="parameter-name">type</dt><dd class="parameter-def">Type of node to construct. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_975e86937621ae4afe6a423219de30d0_1975e86937621ae4afe6a423219de30d0">function xml_node::type</h3><h4>Synopsis</h4><code class="synopsis">node_type type() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets type of node. </para><h4>Returns</h4>Type of node. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_77aea7d8d996ba4f6bd61cc478a4e72d_177aea7d8d996ba4f6bd61cc478a4e72d">function xml_node::document</h3><h4>Synopsis</h4><code class="synopsis">xml_document<Ch>* document() const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets document of which node is a child. </para><h4>Returns</h4>Pointer to document that contains this node, or 0 if there is no parent document. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_7823e36687669e59c2afdf66334ef35a_17823e36687669e59c2afdf66334ef35a">function xml_node::first_node</h3><h4>Synopsis</h4><code class="synopsis">xml_node<Ch>* first_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets first child node, optionally matching node name. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of child to find, or 0 to return first child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found child, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_fcb6e2209b591a36d2dadba20d2bc7cc_1fcb6e2209b591a36d2dadba20d2bc7cc">function xml_node::last_node</h3><h4>Synopsis</h4><code class="synopsis">xml_node<Ch>* last_node(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets last child node, optionally matching node name. Behaviour is undefined if node has no children. Use <a href="#classrapidxml_1_1xml__node_7823e36687669e59c2afdf66334ef35a_17823e36687669e59c2afdf66334ef35a" kindref="member">first_node()</a> to test if node has children. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of child to find, or 0 to return last child regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found child, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_ac2f6886c0107e9d5f156e9542546df6_1ac2f6886c0107e9d5f156e9542546df6">function xml_node::previous_sibling</h3><h4>Synopsis</h4><code class="synopsis">xml_node<Ch>* previous_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets previous sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use <a href="#classrapidxml_1_1xml__base_798e8df7ea53ade4d9f0701017dce80e_1798e8df7ea53ade4d9f0701017dce80e" kindref="member">parent()</a> to test if node has a parent. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found sibling, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_b3ead2cefecc03a813836203e3f6f38f_1b3ead2cefecc03a813836203e3f6f38f">function xml_node::next_sibling</h3><h4>Synopsis</h4><code class="synopsis">xml_node<Ch>* next_sibling(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets next sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use <a href="#classrapidxml_1_1xml__base_798e8df7ea53ade4d9f0701017dce80e_1798e8df7ea53ade4d9f0701017dce80e" kindref="member">parent()</a> to test if node has a parent. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of sibling to find, or 0 to return next sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found sibling, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_5810a09f82f8d53efbe9456286dcec83_15810a09f82f8d53efbe9456286dcec83">function xml_node::first_attribute</h3><h4>Synopsis</h4><code class="synopsis">xml_attribute<Ch>* first_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets first attribute of node, optionally matching attribute name. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of attribute to find, or 0 to return first attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found attribute, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_16953d66751b5b949ee4ee2d9c0bc63a_116953d66751b5b949ee4ee2d9c0bc63a">function xml_node::last_attribute</h3><h4>Synopsis</h4><code class="synopsis">xml_attribute<Ch>* last_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Gets last attribute of node, optionally matching attribute name. </para><h4>Parameters</h4><dl><dt class="parameter-name">name</dt><dd class="parameter-def">Name of attribute to find, or 0 to return last attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero </dd></dl><dl><dt class="parameter-name">name_size</dt><dd class="parameter-def">Size of name, in characters, or 0 to have size calculated automatically from string </dd></dl><dl><dt class="parameter-name">case_sensitive</dt><dd class="parameter-def">Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters </dd></dl><h4>Returns</h4>Pointer to found attribute, or 0 if not found. <p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_a78759bfa429fa2ab6bc5fe617cfa3cf_1a78759bfa429fa2ab6bc5fe617cfa3cf">function xml_node::type</h3><h4>Synopsis</h4><code class="synopsis">void type(node_type type);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Sets type of node. </para><h4>Parameters</h4><dl><dt class="parameter-name">type</dt><dd class="parameter-def">Type of node to set. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_0c39df6617e709eb2fba11300dea63f2_10c39df6617e709eb2fba11300dea63f2">function xml_node::prepend_node</h3><h4>Synopsis</h4><code class="synopsis">void prepend_node(xml_node< Ch > *child);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Prepends a new child node. The prepended child becomes the first child, and all existing children are moved one position back. </para><h4>Parameters</h4><dl><dt class="parameter-name">child</dt><dd class="parameter-def">Node to prepend. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_86de2e22276826089b7baed2599f8dee_186de2e22276826089b7baed2599f8dee">function xml_node::append_node</h3><h4>Synopsis</h4><code class="synopsis">void append_node(xml_node< Ch > *child);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Appends a new child node. The appended child becomes the last child. </para><h4>Parameters</h4><dl><dt class="parameter-name">child</dt><dd class="parameter-def">Node to append. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_780972a57fc447250ab47cc8f421b65e_1780972a57fc447250ab47cc8f421b65e">function xml_node::insert_node</h3><h4>Synopsis</h4><code class="synopsis">void insert_node(xml_node< Ch > *where, xml_node< Ch > *child);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Inserts a new child node at specified place inside the node. All children after and including the specified node are moved one position back. </para><h4>Parameters</h4><dl><dt class="parameter-name">where</dt><dd class="parameter-def">Place where to insert the child, or 0 to insert at the back. </dd></dl><dl><dt class="parameter-name">child</dt><dd class="parameter-def">Node to insert. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_9a31d861e1bddc710839c551a5d2b3a4_19a31d861e1bddc710839c551a5d2b3a4">function xml_node::remove_first_node</h3><h4>Synopsis</h4><code class="synopsis">void remove_first_node();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes first child node. If node has no children, behaviour is undefined. Use <a href="#classrapidxml_1_1xml__node_7823e36687669e59c2afdf66334ef35a_17823e36687669e59c2afdf66334ef35a" kindref="member">first_node()</a> to test if node has children. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_87addf2bc127ee31aa4b5295d3c9b530_187addf2bc127ee31aa4b5295d3c9b530">function xml_node::remove_last_node</h3><h4>Synopsis</h4><code class="synopsis">void remove_last_node();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes last child of the node. If node has no children, behaviour is undefined. Use <a href="#classrapidxml_1_1xml__node_7823e36687669e59c2afdf66334ef35a_17823e36687669e59c2afdf66334ef35a" kindref="member">first_node()</a> to test if node has children. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_9316463a2201631e7e2062b17729f9cd_19316463a2201631e7e2062b17729f9cd">function xml_node::remove_node</h3><h4>Synopsis</h4><code class="synopsis">void remove_node(xml_node< Ch > *where);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes specified child from the node. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_0218147d13e41d5fa60ced4e7a7e9726_10218147d13e41d5fa60ced4e7a7e9726">function xml_node::remove_all_nodes</h3><h4>Synopsis</h4><code class="synopsis">void remove_all_nodes();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes all child nodes (but not attributes). </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_f6dffa513da74cc0be71a7ba84f8265e_1f6dffa513da74cc0be71a7ba84f8265e">function xml_node::prepend_attribute</h3><h4>Synopsis</h4><code class="synopsis">void prepend_attribute(xml_attribute< Ch > *attribute);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Prepends a new attribute to the node. </para><h4>Parameters</h4><dl><dt class="parameter-name">attribute</dt><dd class="parameter-def">Attribute to prepend. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_8fbd4f5ef7169d493da9f8d87ac04b77_18fbd4f5ef7169d493da9f8d87ac04b77">function xml_node::append_attribute</h3><h4>Synopsis</h4><code class="synopsis">void append_attribute(xml_attribute< Ch > *attribute);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Appends a new attribute to the node. </para><h4>Parameters</h4><dl><dt class="parameter-name">attribute</dt><dd class="parameter-def">Attribute to append. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_070d5888b0557fe06a5b24961de1b988_1070d5888b0557fe06a5b24961de1b988">function xml_node::insert_attribute</h3><h4>Synopsis</h4><code class="synopsis">void insert_attribute(xml_attribute< Ch > *where, xml_attribute< Ch > *attribute);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Inserts a new attribute at specified place inside the node. All attributes after and including the specified attribute are moved one position back. </para><h4>Parameters</h4><dl><dt class="parameter-name">where</dt><dd class="parameter-def">Place where to insert the attribute, or 0 to insert at the back. </dd></dl><dl><dt class="parameter-name">attribute</dt><dd class="parameter-def">Attribute to insert. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_4eea4a7f6cb484ca9944f7eafe6e1843_14eea4a7f6cb484ca9944f7eafe6e1843">function xml_node::remove_first_attribute</h3><h4>Synopsis</h4><code class="synopsis">void remove_first_attribute();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes first attribute of the node. If node has no attributes, behaviour is undefined. Use <a href="#classrapidxml_1_1xml__node_5810a09f82f8d53efbe9456286dcec83_15810a09f82f8d53efbe9456286dcec83" kindref="member">first_attribute()</a> to test if node has attributes. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_37d87c4d5d89fa0cf05b72ee8d4cba3b_137d87c4d5d89fa0cf05b72ee8d4cba3b">function xml_node::remove_last_attribute</h3><h4>Synopsis</h4><code class="synopsis">void remove_last_attribute();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes last attribute of the node. If node has no attributes, behaviour is undefined. Use <a href="#classrapidxml_1_1xml__node_5810a09f82f8d53efbe9456286dcec83_15810a09f82f8d53efbe9456286dcec83" kindref="member">first_attribute()</a> to test if node has attributes. </para><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_c75154db2e768c0e5b541fc8cd0775ab_1c75154db2e768c0e5b541fc8cd0775ab">function xml_node::remove_attribute</h3><h4>Synopsis</h4><code class="synopsis">void remove_attribute(xml_attribute< Ch > *where);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes specified attribute from node. </para><h4>Parameters</h4><dl><dt class="parameter-name">where</dt><dd class="parameter-def">Pointer to attribute to be removed. </dd></dl><p/><h3 class="reference-header" id="classrapidxml_1_1xml__node_59e6ad4cfd5e8096c052e71d79561eda_159e6ad4cfd5e8096c052e71d79561eda">function xml_node::remove_all_attributes</h3><h4>Synopsis</h4><code class="synopsis">void remove_all_attributes();
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Removes all attributes of node. </para><p/><h3 class="reference-header" id="namespacerapidxml_6a276b85e2da28c5f9c3dbce61c55682_16a276b85e2da28c5f9c3dbce61c55682">enum node_type</h3><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Enumeration listing all node types produced by the parser. Use <a href="#classrapidxml_1_1xml__node_975e86937621ae4afe6a423219de30d0_1975e86937621ae4afe6a423219de30d0" kindref="member">xml_node::type()</a> function to query node type. </para><h4>Values</h4><dl><dt class="parameter-name">node_document</dt><dd class="parameter-def">A document node. Name and value are empty. </dd></dl><dl><dt class="parameter-name">node_element</dt><dd class="parameter-def">An element node. Name contains element name. Value contains text of first data node. </dd></dl><dl><dt class="parameter-name">node_data</dt><dd class="parameter-def">A data node. Name is empty. Value contains data text. </dd></dl><dl><dt class="parameter-name">node_cdata</dt><dd class="parameter-def">A CDATA node. Name is empty. Value contains data text. </dd></dl><dl><dt class="parameter-name">node_comment</dt><dd class="parameter-def">A comment node. Name is empty. Value contains comment text. </dd></dl><dl><dt class="parameter-name">node_declaration</dt><dd class="parameter-def">A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes. </dd></dl><dl><dt class="parameter-name">node_doctype</dt><dd class="parameter-def">A DOCTYPE node. Name is empty. Value contains DOCTYPE text. </dd></dl><dl><dt class="parameter-name">node_pi</dt><dd class="parameter-def">A PI node. Name contains target. Value contains instructions. </dd></dl><p/><h3 class="reference-header" id="namespacerapidxml_ff5d67f74437199d316d2b2660653ae1_1ff5d67f74437199d316d2b2660653ae1">function parse_error_handler</h3><h4>Synopsis</h4><code class="synopsis">void rapidxml::parse_error_handler(const char *what, void *where);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">When exceptions are disabled by defining RAPIDXML_NO_EXCEPTIONS, this function is called to notify user about the error. It must be defined by the user. <br/><br/>
This function cannot return. If it does, the results are undefined. <br/><br/>
A very simple definition might look like that: <preformatted>
void rapidxml::parse_error_handler(const char *what, void *where)
{
std::cout << "Parse error: " << what << "\n";
std::abort();
}
</preformatted></para><h4>Parameters</h4><dl><dt class="parameter-name">what</dt><dd class="parameter-def">Human readable description of the error. </dd></dl><dl><dt class="parameter-name">where</dt><dd class="parameter-def">Pointer to character data where error was detected. </dd></dl><p/><h3 class="reference-header" id="namespacerapidxml_b94d570fc4c4ab2423813cd0243326b1_1b94d570fc4c4ab2423813cd0243326b1">function print</h3><h4>Synopsis</h4><code class="synopsis">OutIt rapidxml::print(OutIt out, const xml_node< Ch > &node, int flags=0);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Prints XML to given output iterator. </para><h4>Parameters</h4><dl><dt class="parameter-name">out</dt><dd class="parameter-def">Output iterator to print to. </dd></dl><dl><dt class="parameter-name">node</dt><dd class="parameter-def">Node to be printed. Pass xml_document to print entire document. </dd></dl><dl><dt class="parameter-name">flags</dt><dd class="parameter-def">Flags controlling how XML is printed. </dd></dl><h4>Returns</h4>Output iterator pointing to position immediately after last character of printed text. <p/><h3 class="reference-header" id="namespacerapidxml_13bc37d6d1047acb0efdbc1689221a5e_113bc37d6d1047acb0efdbc1689221a5e">function print</h3><h4>Synopsis</h4><code class="synopsis">std::basic_ostream<Ch>& rapidxml::print(std::basic_ostream< Ch > &out, const xml_node< Ch > &node, int flags=0);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Prints XML to given output stream. </para><h4>Parameters</h4><dl><dt class="parameter-name">out</dt><dd class="parameter-def">Output stream to print to. </dd></dl><dl><dt class="parameter-name">node</dt><dd class="parameter-def">Node to be printed. Pass xml_document to print entire document. </dd></dl><dl><dt class="parameter-name">flags</dt><dd class="parameter-def">Flags controlling how XML is printed. </dd></dl><h4>Returns</h4>Output stream. <p/><h3 class="reference-header" id="namespacerapidxml_5619b38000d967fb223b2b0a8c17463a_15619b38000d967fb223b2b0a8c17463a">function operator<<</h3><h4>Synopsis</h4><code class="synopsis">std::basic_ostream<Ch>& rapidxml::operator<<(std::basic_ostream< Ch > &out, const xml_node< Ch > &node);
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Prints formatted XML to given output stream. Uses default printing flags. Use <a href="#namespacerapidxml_b94d570fc4c4ab2423813cd0243326b1_1b94d570fc4c4ab2423813cd0243326b1" kindref="member">print()</a> function to customize printing process. </para><h4>Parameters</h4><dl><dt class="parameter-name">out</dt><dd class="parameter-def">Output stream to print to. </dd></dl><dl><dt class="parameter-name">node</dt><dd class="parameter-def">Node to be printed. </dd></dl><h4>Returns</h4>Output stream. <p/><h3 class="reference-header" id="namespacerapidxml_87e8bbab53702cf3b438bd553c10b6b9_187e8bbab53702cf3b438bd553c10b6b9">
constant
parse_no_data_nodes</h3><h4>Synopsis</h4><code class="synopsis">const int parse_no_data_nodes
= 0x1;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to not create data nodes. Text of first data node will still be placed in value of parent element, unless <a href="#namespacerapidxml_97e2c4fdc04fae17126f9971a4fc993e_197e2c4fdc04fae17126f9971a4fc993e" kindref="member">rapidxml::parse_no_element_values</a> flag is also specified. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_97e2c4fdc04fae17126f9971a4fc993e_197e2c4fdc04fae17126f9971a4fc993e">
constant
parse_no_element_values</h3><h4>Synopsis</h4><code class="synopsis">const int parse_no_element_values
= 0x2;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to not use text of first data node as a value of parent element. Can be combined with other flags by use of | operator. Note that child data nodes of element node take precendence over its value when printing. That is, if element has one or more child data nodes <i>and</i> a value, the value will be ignored. Use <a href="#namespacerapidxml_87e8bbab53702cf3b438bd553c10b6b9_187e8bbab53702cf3b438bd553c10b6b9" kindref="member">rapidxml::parse_no_data_nodes</a> flag to prevent creation of data nodes if you want to manipulate data using values of elements. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_9cae3801e70437cbc410c24bf6be691c_19cae3801e70437cbc410c24bf6be691c">
constant
parse_no_string_terminators</h3><h4>Synopsis</h4><code class="synopsis">const int parse_no_string_terminators
= 0x4;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to not place zero terminators after strings in the source text. By default zero terminators are placed, modifying source text. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_7223b7815c4fb8b42e6e4e77e1ea6b97_17223b7815c4fb8b42e6e4e77e1ea6b97">
constant
parse_no_entity_translation</h3><h4>Synopsis</h4><code class="synopsis">const int parse_no_entity_translation
= 0x8;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to not translate entities in the source text. By default entities are translated, modifying source text. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_ccde57f6054857ee4042a1b4d98c83b9_1ccde57f6054857ee4042a1b4d98c83b9">
constant
parse_no_utf8</h3><h4>Synopsis</h4><code class="synopsis">const int parse_no_utf8
= 0x10;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to disable UTF-8 handling and assume plain 8 bit characters. By default, UTF-8 handling is enabled. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_52e2c934ad9c845a5f4cc49570470556_152e2c934ad9c845a5f4cc49570470556">
constant
parse_declaration_node</h3><h4>Synopsis</h4><code class="synopsis">const int parse_declaration_node
= 0x20;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to create XML declaration node. By default, declaration node is not created. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_0f7479dacbc868456d07897a8c072784_10f7479dacbc868456d07897a8c072784">
constant
parse_comment_nodes</h3><h4>Synopsis</h4><code class="synopsis">const int parse_comment_nodes
= 0x40;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to create comments nodes. By default, comment nodes are not created. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_8e187746ba1ca04f107951ad32df962e_18e187746ba1ca04f107951ad32df962e">
constant
parse_doctype_node</h3><h4>Synopsis</h4><code class="synopsis">const int parse_doctype_node
= 0x80;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to create DOCTYPE node. By default, doctype node is not created. Although W3C specification allows at most one DOCTYPE node, RapidXml will silently accept documents with more than one. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_1c20b2b2b75711cd76423e119c49f830_11c20b2b2b75711cd76423e119c49f830">
constant
parse_pi_nodes</h3><h4>Synopsis</h4><code class="synopsis">const int parse_pi_nodes
= 0x100;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to create PI nodes. By default, PI nodes are not created. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_a5daff9d61c7d4eaf98e4d42efe628ee_1a5daff9d61c7d4eaf98e4d42efe628ee">
constant
parse_validate_closing_tags</h3><h4>Synopsis</h4><code class="synopsis">const int parse_validate_closing_tags
= 0x200;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to validate closing tag names. If not set, name inside closing tag is irrelevant to the parser. By default, closing tags are not validated. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_ac1f06b1afd47b812732fb521b146fd9_1ac1f06b1afd47b812732fb521b146fd9">
constant
parse_trim_whitespace</h3><h4>Synopsis</h4><code class="synopsis">const int parse_trim_whitespace
= 0x400;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to trim all leading and trailing whitespace of data nodes. By default, whitespace is not trimmed. This flag does not cause the parser to modify source text. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_88f95d4e275ba01408fefde83078651b_188f95d4e275ba01408fefde83078651b">
constant
parse_normalize_whitespace</h3><h4>Synopsis</h4><code class="synopsis">const int parse_normalize_whitespace
= 0x800;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flag instructing the parser to condense all whitespace runs of data nodes to a single space character. Trimming of leading and trailing whitespace of data is controlled by <a href="#namespacerapidxml_ac1f06b1afd47b812732fb521b146fd9_1ac1f06b1afd47b812732fb521b146fd9" kindref="member">rapidxml::parse_trim_whitespace</a> flag. By default, whitespace is not normalized. If this flag is specified, source text will be modified. Can be combined with other flags by use of | operator. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_45751cf2f38fd6915f35b3122b46d5b6_145751cf2f38fd6915f35b3122b46d5b6">
constant
parse_default</h3><h4>Synopsis</h4><code class="synopsis">const int parse_default
= 0;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Parse flags which represent default behaviour of the parser. This is always equal to 0, so that all other flags can be simply ored together. Normally there is no need to inconveniently disable flags by anding with their negated (~) values. This also means that meaning of each flag is a <i>negation</i> of the default setting. For example, if flag name is <a href="#namespacerapidxml_ccde57f6054857ee4042a1b4d98c83b9_1ccde57f6054857ee4042a1b4d98c83b9" kindref="member">rapidxml::parse_no_utf8</a>, it means that utf-8 is <i>enabled</i> by default, and using the flag will disable it. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_a97ba1a0a79a6d66f4eef3612508d943_1a97ba1a0a79a6d66f4eef3612508d943">
constant
parse_non_destructive</h3><h4>Synopsis</h4><code class="synopsis">const int parse_non_destructive
= parse_no_string_terminators | parse_no_entity_translation;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">A combination of parse flags that forbids any modifications of the source text. This also results in faster parsing. However, note that the following will occur: <ul><li><para>names and values of nodes will not be zero terminated, you have to use <a href="#classrapidxml_1_1xml__base_0dae694c8f7e4d89f1003e2f3a15a43c_10dae694c8f7e4d89f1003e2f3a15a43c" kindref="member">xml_base::name_size()</a> and <a href="#classrapidxml_1_1xml__base_aed5ae791b7164c1ee5e649198cbb3db_1aed5ae791b7164c1ee5e649198cbb3db" kindref="member">xml_base::value_size()</a> functions to determine where name and value ends </para></li><li><para>entities will not be translated </para></li><li><para>whitespace will not be normalized </para></li></ul>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_398c5476e76102f8bd76c10bb0abbe10_1398c5476e76102f8bd76c10bb0abbe10">
constant
parse_fastest</h3><h4>Synopsis</h4><code class="synopsis">const int parse_fastest
= parse_non_destructive | parse_no_data_nodes;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">A combination of parse flags resulting in fastest possible parsing, without sacrificing important data. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_b4f2515265facb42291570307924bd57_1b4f2515265facb42291570307924bd57">
constant
parse_full</h3><h4>Synopsis</h4><code class="synopsis">const int parse_full
= parse_declaration_node | parse_comment_nodes | parse_doctype_node | parse_pi_nodes | parse_validate_closing_tags;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">A combination of parse flags resulting in largest amount of data being extracted. This usually results in slowest parsing. <br/><br/>
See <a href="#classrapidxml_1_1xml__document_8338ce6042e7b04d5a42144fb446b69c_18338ce6042e7b04d5a42144fb446b69c" kindref="member">xml_document::parse()</a> function. </para><p/><h3 class="reference-header" id="namespacerapidxml_b08b8d4293c203b69ed6c5ae77ac1907_1b08b8d4293c203b69ed6c5ae77ac1907">
constant
print_no_indenting</h3><h4>Synopsis</h4><code class="synopsis">const int print_no_indenting
= 0x1;
</code><h4>Description</h4><para xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Printer flag instructing the printer to suppress indenting of XML. See <a href="#namespacerapidxml_b94d570fc4c4ab2423813cd0243326b1_1b94d570fc4c4ab2423813cd0243326b1" kindref="member">print()</a> function. </para><p/></body></html> | 0 |
coqui_public_repos/STT-models/finnish/itml | coqui_public_repos/STT-models/finnish/itml/v0.1.1/LICENSE | GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
| 0 |
coqui_public_repos/TTS/TTS/tts | coqui_public_repos/TTS/TTS/tts/models/delightful_tts.py | import os
from dataclasses import dataclass, field
from itertools import chain
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.distributed as dist
import torchaudio
from coqpit import Coqpit
from librosa.filters import mel as librosa_mel_fn
from torch import nn
from torch.cuda.amp.autocast_mode import autocast
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torch.utils.data.sampler import WeightedRandomSampler
from trainer.torch import DistributedSampler, DistributedSamplerWrapper
from trainer.trainer_utils import get_optimizer, get_scheduler
from TTS.tts.datasets.dataset import F0Dataset, TTSDataset, _parse_sample
from TTS.tts.layers.delightful_tts.acoustic_model import AcousticModel
from TTS.tts.layers.losses import ForwardSumLoss, VitsDiscriminatorLoss
from TTS.tts.layers.vits.discriminator import VitsDiscriminator
from TTS.tts.models.base_tts import BaseTTSE2E
from TTS.tts.utils.helpers import average_over_durations, compute_attn_prior, rand_segments, segment, sequence_mask
from TTS.tts.utils.speakers import SpeakerManager
from TTS.tts.utils.text.tokenizer import TTSTokenizer
from TTS.tts.utils.visual import plot_alignment, plot_avg_pitch, plot_pitch, plot_spectrogram
from TTS.utils.audio.numpy_transforms import build_mel_basis, compute_f0
from TTS.utils.audio.numpy_transforms import db_to_amp as db_to_amp_numpy
from TTS.utils.audio.numpy_transforms import mel_to_wav as mel_to_wav_numpy
from TTS.utils.audio.processor import AudioProcessor
from TTS.utils.io import load_fsspec
from TTS.vocoder.layers.losses import MultiScaleSTFTLoss
from TTS.vocoder.models.hifigan_generator import HifiganGenerator
from TTS.vocoder.utils.generic_utils import plot_results
def id_to_torch(aux_id, cuda=False):
if aux_id is not None:
aux_id = np.asarray(aux_id)
aux_id = torch.from_numpy(aux_id)
if cuda:
return aux_id.cuda()
return aux_id
def embedding_to_torch(d_vector, cuda=False):
if d_vector is not None:
d_vector = np.asarray(d_vector)
d_vector = torch.from_numpy(d_vector).float()
d_vector = d_vector.squeeze().unsqueeze(0)
if cuda:
return d_vector.cuda()
return d_vector
def numpy_to_torch(np_array, dtype, cuda=False):
if np_array is None:
return None
tensor = torch.as_tensor(np_array, dtype=dtype)
if cuda:
return tensor.cuda()
return tensor
def get_mask_from_lengths(lengths: torch.Tensor) -> torch.Tensor:
batch_size = lengths.shape[0]
max_len = torch.max(lengths).item()
ids = torch.arange(0, max_len, device=lengths.device).unsqueeze(0).expand(batch_size, -1)
mask = ids >= lengths.unsqueeze(1).expand(-1, max_len)
return mask
def pad(input_ele: List[torch.Tensor], max_len: int) -> torch.Tensor:
out_list = torch.jit.annotate(List[torch.Tensor], [])
for batch in input_ele:
if len(batch.shape) == 1:
one_batch_padded = F.pad(batch, (0, max_len - batch.size(0)), "constant", 0.0)
else:
one_batch_padded = F.pad(batch, (0, 0, 0, max_len - batch.size(0)), "constant", 0.0)
out_list.append(one_batch_padded)
out_padded = torch.stack(out_list)
return out_padded
def init_weights(m: nn.Module, mean: float = 0.0, std: float = 0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std)
def stride_lens(lens: torch.Tensor, stride: int = 2) -> torch.Tensor:
return torch.ceil(lens / stride).int()
def initialize_embeddings(shape: Tuple[int]) -> torch.Tensor:
assert len(shape) == 2, "Can only initialize 2-D embedding matrices ..."
return torch.randn(shape) * np.sqrt(2 / shape[1])
# pylint: disable=redefined-outer-name
def calc_same_padding(kernel_size: int) -> Tuple[int, int]:
pad = kernel_size // 2
return (pad, pad - (kernel_size + 1) % 2)
hann_window = {}
mel_basis = {}
@torch.no_grad()
def weights_reset(m: nn.Module):
# check if the current module has reset_parameters and if it is reset the weight
reset_parameters = getattr(m, "reset_parameters", None)
if callable(reset_parameters):
m.reset_parameters()
def get_module_weights_sum(mdl: nn.Module):
dict_sums = {}
for name, w in mdl.named_parameters():
if "weight" in name:
value = w.data.sum().item()
dict_sums[name] = value
return dict_sums
def load_audio(file_path: str):
"""Load the audio file normalized in [-1, 1]
Return Shapes:
- x: :math:`[1, T]`
"""
x, sr = torchaudio.load(
file_path,
)
assert (x > 1).sum() + (x < -1).sum() == 0
return x, sr
def _amp_to_db(x, C=1, clip_val=1e-5):
return torch.log(torch.clamp(x, min=clip_val) * C)
def _db_to_amp(x, C=1):
return torch.exp(x) / C
def amp_to_db(magnitudes):
output = _amp_to_db(magnitudes)
return output
def db_to_amp(magnitudes):
output = _db_to_amp(magnitudes)
return output
def _wav_to_spec(y, n_fft, hop_length, win_length, center=False):
y = y.squeeze(1)
if torch.min(y) < -1.0:
print("min value is ", torch.min(y))
if torch.max(y) > 1.0:
print("max value is ", torch.max(y))
global hann_window # pylint: disable=global-statement
dtype_device = str(y.dtype) + "_" + str(y.device)
wnsize_dtype_device = str(win_length) + "_" + dtype_device
if wnsize_dtype_device not in hann_window:
hann_window[wnsize_dtype_device] = torch.hann_window(win_length).to(dtype=y.dtype, device=y.device)
y = torch.nn.functional.pad(
y.unsqueeze(1),
(int((n_fft - hop_length) / 2), int((n_fft - hop_length) / 2)),
mode="reflect",
)
y = y.squeeze(1)
spec = torch.stft(
y,
n_fft,
hop_length=hop_length,
win_length=win_length,
window=hann_window[wnsize_dtype_device],
center=center,
pad_mode="reflect",
normalized=False,
onesided=True,
return_complex=False,
)
return spec
def wav_to_spec(y, n_fft, hop_length, win_length, center=False):
"""
Args Shapes:
- y : :math:`[B, 1, T]`
Return Shapes:
- spec : :math:`[B,C,T]`
"""
spec = _wav_to_spec(y, n_fft, hop_length, win_length, center=center)
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
return spec
def wav_to_energy(y, n_fft, hop_length, win_length, center=False):
spec = _wav_to_spec(y, n_fft, hop_length, win_length, center=center)
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
return torch.norm(spec, dim=1, keepdim=True)
def name_mel_basis(spec, n_fft, fmax):
n_fft_len = f"{n_fft}_{fmax}_{spec.dtype}_{spec.device}"
return n_fft_len
def spec_to_mel(spec, n_fft, num_mels, sample_rate, fmin, fmax):
"""
Args Shapes:
- spec : :math:`[B,C,T]`
Return Shapes:
- mel : :math:`[B,C,T]`
"""
global mel_basis # pylint: disable=global-statement
mel_basis_key = name_mel_basis(spec, n_fft, fmax)
# pylint: disable=too-many-function-args
if mel_basis_key not in mel_basis:
# pylint: disable=missing-kwoa
mel = librosa_mel_fn(sample_rate, n_fft, num_mels, fmin, fmax)
mel_basis[mel_basis_key] = torch.from_numpy(mel).to(dtype=spec.dtype, device=spec.device)
mel = torch.matmul(mel_basis[mel_basis_key], spec)
mel = amp_to_db(mel)
return mel
def wav_to_mel(y, n_fft, num_mels, sample_rate, hop_length, win_length, fmin, fmax, center=False):
"""
Args Shapes:
- y : :math:`[B, 1, T_y]`
Return Shapes:
- spec : :math:`[B,C,T_spec]`
"""
y = y.squeeze(1)
if torch.min(y) < -1.0:
print("min value is ", torch.min(y))
if torch.max(y) > 1.0:
print("max value is ", torch.max(y))
global mel_basis, hann_window # pylint: disable=global-statement
mel_basis_key = name_mel_basis(y, n_fft, fmax)
wnsize_dtype_device = str(win_length) + "_" + str(y.dtype) + "_" + str(y.device)
if mel_basis_key not in mel_basis:
# pylint: disable=missing-kwoa
mel = librosa_mel_fn(
sr=sample_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax
) # pylint: disable=too-many-function-args
mel_basis[mel_basis_key] = torch.from_numpy(mel).to(dtype=y.dtype, device=y.device)
if wnsize_dtype_device not in hann_window:
hann_window[wnsize_dtype_device] = torch.hann_window(win_length).to(dtype=y.dtype, device=y.device)
y = torch.nn.functional.pad(
y.unsqueeze(1),
(int((n_fft - hop_length) / 2), int((n_fft - hop_length) / 2)),
mode="reflect",
)
y = y.squeeze(1)
spec = torch.stft(
y,
n_fft,
hop_length=hop_length,
win_length=win_length,
window=hann_window[wnsize_dtype_device],
center=center,
pad_mode="reflect",
normalized=False,
onesided=True,
return_complex=False,
)
spec = torch.sqrt(spec.pow(2).sum(-1) + 1e-6)
spec = torch.matmul(mel_basis[mel_basis_key], spec)
spec = amp_to_db(spec)
return spec
##############################
# DATASET
##############################
def get_attribute_balancer_weights(items: list, attr_name: str, multi_dict: dict = None):
"""Create balancer weight for torch WeightedSampler"""
attr_names_samples = np.array([item[attr_name] for item in items])
unique_attr_names = np.unique(attr_names_samples).tolist()
attr_idx = [unique_attr_names.index(l) for l in attr_names_samples]
attr_count = np.array([len(np.where(attr_names_samples == l)[0]) for l in unique_attr_names])
weight_attr = 1.0 / attr_count
dataset_samples_weight = np.array([weight_attr[l] for l in attr_idx])
dataset_samples_weight = dataset_samples_weight / np.linalg.norm(dataset_samples_weight)
if multi_dict is not None:
multiplier_samples = np.array([multi_dict.get(item[attr_name], 1.0) for item in items])
dataset_samples_weight *= multiplier_samples
return (
torch.from_numpy(dataset_samples_weight).float(),
unique_attr_names,
np.unique(dataset_samples_weight).tolist(),
)
class ForwardTTSE2eF0Dataset(F0Dataset):
"""Override F0Dataset to avoid slow computing of pitches"""
def __init__(
self,
ap,
samples: Union[List[List], List[Dict]],
verbose=False,
cache_path: str = None,
precompute_num_workers=0,
normalize_f0=True,
):
super().__init__(
samples=samples,
ap=ap,
verbose=verbose,
cache_path=cache_path,
precompute_num_workers=precompute_num_workers,
normalize_f0=normalize_f0,
)
def _compute_and_save_pitch(self, wav_file, pitch_file=None):
wav, _ = load_audio(wav_file)
f0 = compute_f0(
x=wav.numpy()[0],
sample_rate=self.ap.sample_rate,
hop_length=self.ap.hop_length,
pitch_fmax=self.ap.pitch_fmax,
pitch_fmin=self.ap.pitch_fmin,
win_length=self.ap.win_length,
)
# skip the last F0 value to align with the spectrogram
if wav.shape[1] % self.ap.hop_length != 0:
f0 = f0[:-1]
if pitch_file:
np.save(pitch_file, f0)
return f0
def compute_or_load(self, wav_file, audio_name):
"""
compute pitch and return a numpy array of pitch values
"""
pitch_file = self.create_pitch_file_path(audio_name, self.cache_path)
if not os.path.exists(pitch_file):
pitch = self._compute_and_save_pitch(wav_file=wav_file, pitch_file=pitch_file)
else:
pitch = np.load(pitch_file)
return pitch.astype(np.float32)
class ForwardTTSE2eDataset(TTSDataset):
def __init__(self, *args, **kwargs):
# don't init the default F0Dataset in TTSDataset
compute_f0 = kwargs.pop("compute_f0", False)
kwargs["compute_f0"] = False
self.attn_prior_cache_path = kwargs.pop("attn_prior_cache_path")
super().__init__(*args, **kwargs)
self.compute_f0 = compute_f0
self.pad_id = self.tokenizer.characters.pad_id
self.ap = kwargs["ap"]
if self.compute_f0:
self.f0_dataset = ForwardTTSE2eF0Dataset(
ap=self.ap,
samples=self.samples,
cache_path=kwargs["f0_cache_path"],
precompute_num_workers=kwargs["precompute_num_workers"],
)
if self.attn_prior_cache_path is not None:
os.makedirs(self.attn_prior_cache_path, exist_ok=True)
def __getitem__(self, idx):
item = self.samples[idx]
rel_wav_path = Path(item["audio_file"]).relative_to(item["root_path"]).with_suffix("")
rel_wav_path = str(rel_wav_path).replace("/", "_")
raw_text = item["text"]
wav, _ = load_audio(item["audio_file"])
wav_filename = os.path.basename(item["audio_file"])
try:
token_ids = self.get_token_ids(idx, item["text"])
except:
print(idx, item)
# pylint: disable=raise-missing-from
raise OSError
f0 = None
if self.compute_f0:
f0 = self.get_f0(idx)["f0"]
# after phonemization the text length may change
# this is a shameful 🤭 hack to prevent longer phonemes
# TODO: find a better fix
if len(token_ids) > self.max_text_len or wav.shape[1] < self.min_audio_len:
self.rescue_item_idx += 1
return self.__getitem__(self.rescue_item_idx)
attn_prior = None
if self.attn_prior_cache_path is not None:
attn_prior = self.load_or_compute_attn_prior(token_ids, wav, rel_wav_path)
return {
"raw_text": raw_text,
"token_ids": token_ids,
"token_len": len(token_ids),
"wav": wav,
"pitch": f0,
"wav_file": wav_filename,
"speaker_name": item["speaker_name"],
"language_name": item["language"],
"attn_prior": attn_prior,
"audio_unique_name": item["audio_unique_name"],
}
def load_or_compute_attn_prior(self, token_ids, wav, rel_wav_path):
"""Load or compute and save the attention prior."""
attn_prior_file = os.path.join(self.attn_prior_cache_path, f"{rel_wav_path}.npy")
# pylint: disable=no-else-return
if os.path.exists(attn_prior_file):
return np.load(attn_prior_file)
else:
token_len = len(token_ids)
mel_len = wav.shape[1] // self.ap.hop_length
attn_prior = compute_attn_prior(token_len, mel_len)
np.save(attn_prior_file, attn_prior)
return attn_prior
@property
def lengths(self):
lens = []
for item in self.samples:
_, wav_file, *_ = _parse_sample(item)
audio_len = os.path.getsize(wav_file) / 16 * 8 # assuming 16bit audio
lens.append(audio_len)
return lens
def collate_fn(self, batch):
"""
Return Shapes:
- tokens: :math:`[B, T]`
- token_lens :math:`[B]`
- token_rel_lens :math:`[B]`
- pitch :math:`[B, T]`
- waveform: :math:`[B, 1, T]`
- waveform_lens: :math:`[B]`
- waveform_rel_lens: :math:`[B]`
- speaker_names: :math:`[B]`
- language_names: :math:`[B]`
- audiofile_paths: :math:`[B]`
- raw_texts: :math:`[B]`
- attn_prior: :math:`[[T_token, T_mel]]`
"""
B = len(batch)
batch = {k: [dic[k] for dic in batch] for k in batch[0]}
max_text_len = max([len(x) for x in batch["token_ids"]])
token_lens = torch.LongTensor(batch["token_len"])
token_rel_lens = token_lens / token_lens.max()
wav_lens = [w.shape[1] for w in batch["wav"]]
wav_lens = torch.LongTensor(wav_lens)
wav_lens_max = torch.max(wav_lens)
wav_rel_lens = wav_lens / wav_lens_max
pitch_padded = None
if self.compute_f0:
pitch_lens = [p.shape[0] for p in batch["pitch"]]
pitch_lens = torch.LongTensor(pitch_lens)
pitch_lens_max = torch.max(pitch_lens)
pitch_padded = torch.FloatTensor(B, 1, pitch_lens_max)
pitch_padded = pitch_padded.zero_() + self.pad_id
token_padded = torch.LongTensor(B, max_text_len)
wav_padded = torch.FloatTensor(B, 1, wav_lens_max)
token_padded = token_padded.zero_() + self.pad_id
wav_padded = wav_padded.zero_() + self.pad_id
for i in range(B):
token_ids = batch["token_ids"][i]
token_padded[i, : batch["token_len"][i]] = torch.LongTensor(token_ids)
wav = batch["wav"][i]
wav_padded[i, :, : wav.size(1)] = torch.FloatTensor(wav)
if self.compute_f0:
pitch = batch["pitch"][i]
pitch_padded[i, 0, : len(pitch)] = torch.FloatTensor(pitch)
return {
"text_input": token_padded,
"text_lengths": token_lens,
"text_rel_lens": token_rel_lens,
"pitch": pitch_padded,
"waveform": wav_padded, # (B x T)
"waveform_lens": wav_lens, # (B)
"waveform_rel_lens": wav_rel_lens,
"speaker_names": batch["speaker_name"],
"language_names": batch["language_name"],
"audio_unique_names": batch["audio_unique_name"],
"audio_files": batch["wav_file"],
"raw_text": batch["raw_text"],
"attn_priors": batch["attn_prior"] if batch["attn_prior"][0] is not None else None,
}
##############################
# CONFIG DEFINITIONS
##############################
@dataclass
class VocoderConfig(Coqpit):
resblock_type_decoder: str = "1"
resblock_kernel_sizes_decoder: List[int] = field(default_factory=lambda: [3, 7, 11])
resblock_dilation_sizes_decoder: List[List[int]] = field(default_factory=lambda: [[1, 3, 5], [1, 3, 5], [1, 3, 5]])
upsample_rates_decoder: List[int] = field(default_factory=lambda: [8, 8, 2, 2])
upsample_initial_channel_decoder: int = 512
upsample_kernel_sizes_decoder: List[int] = field(default_factory=lambda: [16, 16, 4, 4])
use_spectral_norm_discriminator: bool = False
upsampling_rates_discriminator: List[int] = field(default_factory=lambda: [4, 4, 4, 4])
periods_discriminator: List[int] = field(default_factory=lambda: [2, 3, 5, 7, 11])
pretrained_model_path: Optional[str] = None
@dataclass
class DelightfulTtsAudioConfig(Coqpit):
sample_rate: int = 22050
hop_length: int = 256
win_length: int = 1024
fft_size: int = 1024
mel_fmin: float = 0.0
mel_fmax: float = 8000
num_mels: int = 100
pitch_fmax: float = 640.0
pitch_fmin: float = 1.0
resample: bool = False
preemphasis: float = 0.0
ref_level_db: int = 20
do_sound_norm: bool = False
log_func: str = "np.log10"
do_trim_silence: bool = True
trim_db: int = 45
do_rms_norm: bool = False
db_level: float = None
power: float = 1.5
griffin_lim_iters: int = 60
spec_gain: int = 20
do_amp_to_db_linear: bool = True
do_amp_to_db_mel: bool = True
min_level_db: int = -100
max_norm: float = 4.0
@dataclass
class DelightfulTtsArgs(Coqpit):
num_chars: int = 100
spec_segment_size: int = 32
n_hidden_conformer_encoder: int = 512
n_layers_conformer_encoder: int = 6
n_heads_conformer_encoder: int = 8
dropout_conformer_encoder: float = 0.1
kernel_size_conv_mod_conformer_encoder: int = 7
kernel_size_depthwise_conformer_encoder: int = 7
lrelu_slope: float = 0.3
n_hidden_conformer_decoder: int = 512
n_layers_conformer_decoder: int = 6
n_heads_conformer_decoder: int = 8
dropout_conformer_decoder: float = 0.1
kernel_size_conv_mod_conformer_decoder: int = 11
kernel_size_depthwise_conformer_decoder: int = 11
bottleneck_size_p_reference_encoder: int = 4
bottleneck_size_u_reference_encoder: int = 512
ref_enc_filters_reference_encoder = [32, 32, 64, 64, 128, 128]
ref_enc_size_reference_encoder: int = 3
ref_enc_strides_reference_encoder = [1, 2, 1, 2, 1]
ref_enc_pad_reference_encoder = [1, 1]
ref_enc_gru_size_reference_encoder: int = 32
ref_attention_dropout_reference_encoder: float = 0.2
token_num_reference_encoder: int = 32
predictor_kernel_size_reference_encoder: int = 5
n_hidden_variance_adaptor: int = 512
kernel_size_variance_adaptor: int = 5
dropout_variance_adaptor: float = 0.5
n_bins_variance_adaptor: int = 256
emb_kernel_size_variance_adaptor: int = 3
use_speaker_embedding: bool = False
num_speakers: int = 0
speakers_file: str = None
d_vector_file: str = None
speaker_embedding_channels: int = 384
use_d_vector_file: bool = False
d_vector_dim: int = 0
freeze_vocoder: bool = False
freeze_text_encoder: bool = False
freeze_duration_predictor: bool = False
freeze_pitch_predictor: bool = False
freeze_energy_predictor: bool = False
freeze_basis_vectors_predictor: bool = False
freeze_decoder: bool = False
length_scale: float = 1.0
##############################
# MODEL DEFINITION
##############################
class DelightfulTTS(BaseTTSE2E):
"""
Paper::
https://arxiv.org/pdf/2110.12612.pdf
Paper Abstract::
This paper describes the Microsoft end-to-end neural text to speech (TTS) system: DelightfulTTS for Blizzard Challenge 2021.
The goal of this challenge is to synthesize natural and high-quality speech from text, and we approach this goal in two perspectives:
The first is to directly model and generate waveform in 48 kHz sampling rate, which brings higher perception quality than previous systems
with 16 kHz or 24 kHz sampling rate; The second is to model the variation information in speech through a systematic design, which improves
the prosody and naturalness. Specifically, for 48 kHz modeling, we predict 16 kHz mel-spectrogram in acoustic model, and
propose a vocoder called HiFiNet to directly generate 48 kHz waveform from predicted 16 kHz mel-spectrogram, which can better trade off training
efficiency, modelling stability and voice quality. We model variation information systematically from both explicit (speaker ID, language ID, pitch and duration) and
implicit (utterance-level and phoneme-level prosody) perspectives: 1) For speaker and language ID, we use lookup embedding in training and
inference; 2) For pitch and duration, we extract the values from paired text-speech data in training and use two predictors to predict the values in inference; 3)
For utterance-level and phoneme-level prosody, we use two reference encoders to extract the values in training, and use two separate predictors to predict the values in inference.
Additionally, we introduce an improved Conformer block to better model the local and global dependency in acoustic model. For task SH1, DelightfulTTS achieves 4.17 mean score in MOS test
and 4.35 in SMOS test, which indicates the effectiveness of our proposed system
Model training::
text --> ForwardTTS() --> spec_hat --> rand_seg_select()--> GANVocoder() --> waveform_seg
spec --------^
Examples:
>>> from TTS.tts.models.forward_tts_e2e import ForwardTTSE2e, ForwardTTSE2eConfig
>>> config = ForwardTTSE2eConfig()
>>> model = ForwardTTSE2e(config)
"""
# pylint: disable=dangerous-default-value
def __init__(
self,
config: Coqpit,
ap,
tokenizer: "TTSTokenizer" = None,
speaker_manager: SpeakerManager = None,
):
super().__init__(config=config, ap=ap, tokenizer=tokenizer, speaker_manager=speaker_manager)
self.ap = ap
self._set_model_args(config)
self.init_multispeaker(config)
self.binary_loss_weight = None
self.args.out_channels = self.config.audio.num_mels
self.args.num_mels = self.config.audio.num_mels
self.acoustic_model = AcousticModel(args=self.args, tokenizer=tokenizer, speaker_manager=speaker_manager)
self.waveform_decoder = HifiganGenerator(
self.config.audio.num_mels,
1,
self.config.vocoder.resblock_type_decoder,
self.config.vocoder.resblock_dilation_sizes_decoder,
self.config.vocoder.resblock_kernel_sizes_decoder,
self.config.vocoder.upsample_kernel_sizes_decoder,
self.config.vocoder.upsample_initial_channel_decoder,
self.config.vocoder.upsample_rates_decoder,
inference_padding=0,
# cond_channels=self.embedded_speaker_dim,
conv_pre_weight_norm=False,
conv_post_weight_norm=False,
conv_post_bias=False,
)
if self.config.init_discriminator:
self.disc = VitsDiscriminator(
use_spectral_norm=self.config.vocoder.use_spectral_norm_discriminator,
periods=self.config.vocoder.periods_discriminator,
)
@property
def device(self):
return next(self.parameters()).device
@property
def energy_scaler(self):
return self.acoustic_model.energy_scaler
@property
def length_scale(self):
return self.acoustic_model.length_scale
@length_scale.setter
def length_scale(self, value):
self.acoustic_model.length_scale = value
@property
def pitch_mean(self):
return self.acoustic_model.pitch_mean
@pitch_mean.setter
def pitch_mean(self, value):
self.acoustic_model.pitch_mean = value
@property
def pitch_std(self):
return self.acoustic_model.pitch_std
@pitch_std.setter
def pitch_std(self, value):
self.acoustic_model.pitch_std = value
@property
def mel_basis(self):
return build_mel_basis(
sample_rate=self.ap.sample_rate,
fft_size=self.ap.fft_size,
num_mels=self.ap.num_mels,
mel_fmax=self.ap.mel_fmax,
mel_fmin=self.ap.mel_fmin,
) # pylint: disable=function-redefined
def init_for_training(self) -> None:
self.train_disc = ( # pylint: disable=attribute-defined-outside-init
self.config.steps_to_start_discriminator <= 0
) # pylint: disable=attribute-defined-outside-init
self.update_energy_scaler = True # pylint: disable=attribute-defined-outside-init
def init_multispeaker(self, config: Coqpit):
"""Init for multi-speaker training.
Args:
config (Coqpit): Model configuration.
"""
self.embedded_speaker_dim = 0
self.num_speakers = self.args.num_speakers
self.audio_transform = None
if self.speaker_manager:
self.num_speakers = self.speaker_manager.num_speakers
self.args.num_speakers = self.speaker_manager.num_speakers
if self.args.use_speaker_embedding:
self._init_speaker_embedding()
if self.args.use_d_vector_file:
self._init_d_vector()
def _init_speaker_embedding(self):
# pylint: disable=attribute-defined-outside-init
if self.num_speakers > 0:
print(" > initialization of speaker-embedding layers.")
self.embedded_speaker_dim = self.args.speaker_embedding_channels
self.args.embedded_speaker_dim = self.args.speaker_embedding_channels
def _init_d_vector(self):
# pylint: disable=attribute-defined-outside-init
if hasattr(self, "emb_g"):
raise ValueError("[!] Speaker embedding layer already initialized before d_vector settings.")
self.embedded_speaker_dim = self.args.d_vector_dim
self.args.embedded_speaker_dim = self.args.d_vector_dim
def _freeze_layers(self):
if self.args.freeze_vocoder:
for param in self.vocoder.paramseters():
param.requires_grad = False
if self.args.freeze_text_encoder:
for param in self.text_encoder.parameters():
param.requires_grad = False
if self.args.freeze_duration_predictor:
for param in self.durarion_predictor.parameters():
param.requires_grad = False
if self.args.freeze_pitch_predictor:
for param in self.pitch_predictor.parameters():
param.requires_grad = False
if self.args.freeze_energy_predictor:
for param in self.energy_predictor.parameters():
param.requires_grad = False
if self.args.freeze_decoder:
for param in self.decoder.parameters():
param.requires_grad = False
def forward(
self,
x: torch.LongTensor,
x_lengths: torch.LongTensor,
spec_lengths: torch.LongTensor,
spec: torch.FloatTensor,
waveform: torch.FloatTensor,
pitch: torch.FloatTensor = None,
energy: torch.FloatTensor = None,
attn_priors: torch.FloatTensor = None,
d_vectors: torch.FloatTensor = None,
speaker_idx: torch.LongTensor = None,
) -> Dict:
"""Model's forward pass.
Args:
x (torch.LongTensor): Input character sequences.
x_lengths (torch.LongTensor): Input sequence lengths.
spec_lengths (torch.LongTensor): Spectrogram sequnce lengths. Defaults to None.
spec (torch.FloatTensor): Spectrogram frames. Only used when the alignment network is on. Defaults to None.
waveform (torch.FloatTensor): Waveform. Defaults to None.
pitch (torch.FloatTensor): Pitch values for each spectrogram frame. Only used when the pitch predictor is on. Defaults to None.
energy (torch.FloatTensor): Spectral energy values for each spectrogram frame. Only used when the energy predictor is on. Defaults to None.
attn_priors (torch.FloatTentrasor): Attention priors for the aligner network. Defaults to None.
aux_input (Dict): Auxiliary model inputs for multi-speaker training. Defaults to `{"d_vectors": 0, "speaker_ids": None}`.
Shapes:
- x: :math:`[B, T_max]`
- x_lengths: :math:`[B]`
- spec_lengths: :math:`[B]`
- spec: :math:`[B, T_max2, C_spec]`
- waveform: :math:`[B, 1, T_max2 * hop_length]`
- g: :math:`[B, C]`
- pitch: :math:`[B, 1, T_max2]`
- energy: :math:`[B, 1, T_max2]`
"""
encoder_outputs = self.acoustic_model(
tokens=x,
src_lens=x_lengths,
mel_lens=spec_lengths,
mels=spec,
pitches=pitch,
energies=energy,
attn_priors=attn_priors,
d_vectors=d_vectors,
speaker_idx=speaker_idx,
)
# use mel-spec from the decoder
vocoder_input = encoder_outputs["model_outputs"] # [B, T_max2, C_mel]
vocoder_input_slices, slice_ids = rand_segments(
x=vocoder_input.transpose(1, 2),
x_lengths=spec_lengths,
segment_size=self.args.spec_segment_size,
let_short_samples=True,
pad_short=True,
)
if encoder_outputs["spk_emb"] is not None:
g = encoder_outputs["spk_emb"].unsqueeze(-1)
else:
g = None
vocoder_output = self.waveform_decoder(x=vocoder_input_slices.detach(), g=g)
wav_seg = segment(
waveform,
slice_ids * self.ap.hop_length,
self.args.spec_segment_size * self.ap.hop_length,
pad_short=True,
)
model_outputs = {**encoder_outputs}
model_outputs["acoustic_model_outputs"] = encoder_outputs["model_outputs"]
model_outputs["model_outputs"] = vocoder_output
model_outputs["waveform_seg"] = wav_seg
model_outputs["slice_ids"] = slice_ids
return model_outputs
@torch.no_grad()
def inference(
self, x, aux_input={"d_vectors": None, "speaker_ids": None}, pitch_transform=None, energy_transform=None
):
encoder_outputs = self.acoustic_model.inference(
tokens=x,
d_vectors=aux_input["d_vectors"],
speaker_idx=aux_input["speaker_ids"],
pitch_transform=pitch_transform,
energy_transform=energy_transform,
p_control=None,
d_control=None,
)
vocoder_input = encoder_outputs["model_outputs"].transpose(1, 2) # [B, T_max2, C_mel] -> [B, C_mel, T_max2]
if encoder_outputs["spk_emb"] is not None:
g = encoder_outputs["spk_emb"].unsqueeze(-1)
else:
g = None
vocoder_output = self.waveform_decoder(x=vocoder_input, g=g)
model_outputs = {**encoder_outputs}
model_outputs["model_outputs"] = vocoder_output
return model_outputs
@torch.no_grad()
def inference_spec_decoder(self, x, aux_input={"d_vectors": None, "speaker_ids": None}):
encoder_outputs = self.acoustic_model.inference(
tokens=x,
d_vectors=aux_input["d_vectors"],
speaker_idx=aux_input["speaker_ids"],
)
model_outputs = {**encoder_outputs}
return model_outputs
def train_step(self, batch: dict, criterion: nn.Module, optimizer_idx: int):
if optimizer_idx == 0:
tokens = batch["text_input"]
token_lenghts = batch["text_lengths"]
mel = batch["mel_input"]
mel_lens = batch["mel_lengths"]
waveform = batch["waveform"] # [B, T, C] -> [B, C, T]
pitch = batch["pitch"]
d_vectors = batch["d_vectors"]
speaker_ids = batch["speaker_ids"]
attn_priors = batch["attn_priors"]
energy = batch["energy"]
# generator pass
outputs = self.forward(
x=tokens,
x_lengths=token_lenghts,
spec_lengths=mel_lens,
spec=mel,
waveform=waveform,
pitch=pitch,
energy=energy,
attn_priors=attn_priors,
d_vectors=d_vectors,
speaker_idx=speaker_ids,
)
# cache tensors for the generator pass
self.model_outputs_cache = outputs # pylint: disable=attribute-defined-outside-init
if self.train_disc:
# compute scores and features
scores_d_fake, _, scores_d_real, _ = self.disc(
outputs["model_outputs"].detach(), outputs["waveform_seg"]
)
# compute loss
with autocast(enabled=False): # use float32 for the criterion
loss_dict = criterion[optimizer_idx](
scores_disc_fake=scores_d_fake,
scores_disc_real=scores_d_real,
)
return outputs, loss_dict
return None, None
if optimizer_idx == 1:
mel = batch["mel_input"]
# compute melspec segment
with autocast(enabled=False):
mel_slice = segment(
mel.float(), self.model_outputs_cache["slice_ids"], self.args.spec_segment_size, pad_short=True
)
mel_slice_hat = wav_to_mel(
y=self.model_outputs_cache["model_outputs"].float(),
n_fft=self.ap.fft_size,
sample_rate=self.ap.sample_rate,
num_mels=self.ap.num_mels,
hop_length=self.ap.hop_length,
win_length=self.ap.win_length,
fmin=self.ap.mel_fmin,
fmax=self.ap.mel_fmax,
center=False,
)
scores_d_fake = None
feats_d_fake = None
feats_d_real = None
if self.train_disc:
# compute discriminator scores and features
scores_d_fake, feats_d_fake, _, feats_d_real = self.disc(
self.model_outputs_cache["model_outputs"], self.model_outputs_cache["waveform_seg"]
)
# compute losses
with autocast(enabled=True): # use float32 for the criterion
loss_dict = criterion[optimizer_idx](
mel_output=self.model_outputs_cache["acoustic_model_outputs"].transpose(1, 2),
mel_target=batch["mel_input"],
mel_lens=batch["mel_lengths"],
dur_output=self.model_outputs_cache["dr_log_pred"],
dur_target=self.model_outputs_cache["dr_log_target"].detach(),
pitch_output=self.model_outputs_cache["pitch_pred"],
pitch_target=self.model_outputs_cache["pitch_target"],
energy_output=self.model_outputs_cache["energy_pred"],
energy_target=self.model_outputs_cache["energy_target"],
src_lens=batch["text_lengths"],
waveform=self.model_outputs_cache["waveform_seg"],
waveform_hat=self.model_outputs_cache["model_outputs"],
p_prosody_ref=self.model_outputs_cache["p_prosody_ref"],
p_prosody_pred=self.model_outputs_cache["p_prosody_pred"],
u_prosody_ref=self.model_outputs_cache["u_prosody_ref"],
u_prosody_pred=self.model_outputs_cache["u_prosody_pred"],
aligner_logprob=self.model_outputs_cache["aligner_logprob"],
aligner_hard=self.model_outputs_cache["aligner_mas"],
aligner_soft=self.model_outputs_cache["aligner_soft"],
binary_loss_weight=self.binary_loss_weight,
feats_fake=feats_d_fake,
feats_real=feats_d_real,
scores_fake=scores_d_fake,
spec_slice=mel_slice,
spec_slice_hat=mel_slice_hat,
skip_disc=not self.train_disc,
)
loss_dict["avg_text_length"] = batch["text_lengths"].float().mean()
loss_dict["avg_mel_length"] = batch["mel_lengths"].float().mean()
loss_dict["avg_text_batch_occupancy"] = (
batch["text_lengths"].float() / batch["text_lengths"].float().max()
).mean()
loss_dict["avg_mel_batch_occupancy"] = (
batch["mel_lengths"].float() / batch["mel_lengths"].float().max()
).mean()
return self.model_outputs_cache, loss_dict
raise ValueError(" [!] Unexpected `optimizer_idx`.")
def eval_step(self, batch: dict, criterion: nn.Module, optimizer_idx: int):
return self.train_step(batch, criterion, optimizer_idx)
def _log(self, batch, outputs, name_prefix="train"):
figures, audios = {}, {}
# encoder outputs
model_outputs = outputs[1]["acoustic_model_outputs"]
alignments = outputs[1]["alignments"]
mel_input = batch["mel_input"]
pred_spec = model_outputs[0].data.cpu().numpy()
gt_spec = mel_input[0].data.cpu().numpy()
align_img = alignments[0].data.cpu().numpy()
figures = {
"prediction": plot_spectrogram(pred_spec, None, output_fig=False),
"ground_truth": plot_spectrogram(gt_spec.T, None, output_fig=False),
"alignment": plot_alignment(align_img, output_fig=False),
}
# plot pitch figures
pitch_avg = abs(outputs[1]["pitch_target"][0, 0].data.cpu().numpy())
pitch_avg_hat = abs(outputs[1]["pitch_pred"][0, 0].data.cpu().numpy())
chars = self.tokenizer.decode(batch["text_input"][0].data.cpu().numpy())
pitch_figures = {
"pitch_ground_truth": plot_avg_pitch(pitch_avg, chars, output_fig=False),
"pitch_avg_predicted": plot_avg_pitch(pitch_avg_hat, chars, output_fig=False),
}
figures.update(pitch_figures)
# plot energy figures
energy_avg = abs(outputs[1]["energy_target"][0, 0].data.cpu().numpy())
energy_avg_hat = abs(outputs[1]["energy_pred"][0, 0].data.cpu().numpy())
chars = self.tokenizer.decode(batch["text_input"][0].data.cpu().numpy())
energy_figures = {
"energy_ground_truth": plot_avg_pitch(energy_avg, chars, output_fig=False),
"energy_avg_predicted": plot_avg_pitch(energy_avg_hat, chars, output_fig=False),
}
figures.update(energy_figures)
# plot the attention mask computed from the predicted durations
alignments_hat = outputs[1]["alignments_dp"][0].data.cpu().numpy()
figures["alignment_hat"] = plot_alignment(alignments_hat.T, output_fig=False)
# Sample audio
encoder_audio = mel_to_wav_numpy(
mel=db_to_amp_numpy(x=pred_spec.T, gain=1, base=None), mel_basis=self.mel_basis, **self.config.audio
)
audios[f"{name_prefix}/encoder_audio"] = encoder_audio
# vocoder outputs
y_hat = outputs[1]["model_outputs"]
y = outputs[1]["waveform_seg"]
vocoder_figures = plot_results(y_hat=y_hat, y=y, ap=self.ap, name_prefix=name_prefix)
figures.update(vocoder_figures)
sample_voice = y_hat[0].squeeze(0).detach().cpu().numpy()
audios[f"{name_prefix}/vocoder_audio"] = sample_voice
return figures, audios
def train_log(
self, batch: dict, outputs: dict, logger: "Logger", assets: dict, steps: int
): # pylint: disable=no-self-use, unused-argument
"""Create visualizations and waveform examples.
For example, here you can plot spectrograms and generate sample sample waveforms from these spectrograms to
be projected onto Tensorboard.
Args:
batch (Dict): Model inputs used at the previous training step.
outputs (Dict): Model outputs generated at the previous training step.
Returns:
Tuple[Dict, np.ndarray]: training plots and output waveform.
"""
figures, audios = self._log(batch=batch, outputs=outputs, name_prefix="vocoder/")
logger.train_figures(steps, figures)
logger.train_audios(steps, audios, self.ap.sample_rate)
def eval_log(self, batch: dict, outputs: dict, logger: "Logger", assets: dict, steps: int) -> None:
figures, audios = self._log(batch=batch, outputs=outputs, name_prefix="vocoder/")
logger.eval_figures(steps, figures)
logger.eval_audios(steps, audios, self.ap.sample_rate)
def get_aux_input_from_test_sentences(self, sentence_info):
if hasattr(self.config, "model_args"):
config = self.config.model_args
else:
config = self.config
# extract speaker and language info
text, speaker_name, style_wav = None, None, None
if isinstance(sentence_info, list):
if len(sentence_info) == 1:
text = sentence_info[0]
elif len(sentence_info) == 2:
text, speaker_name = sentence_info
elif len(sentence_info) == 3:
text, speaker_name, style_wav = sentence_info
else:
text = sentence_info
# get speaker id/d_vector
speaker_id, d_vector = None, None
if hasattr(self, "speaker_manager"):
if config.use_d_vector_file:
if speaker_name is None:
d_vector = self.speaker_manager.get_random_embedding()
else:
d_vector = self.speaker_manager.get_mean_embedding(speaker_name, num_samples=None, randomize=False)
elif config.use_speaker_embedding:
if speaker_name is None:
speaker_id = self.speaker_manager.get_random_id()
else:
speaker_id = self.speaker_manager.name_to_id[speaker_name]
return {"text": text, "speaker_id": speaker_id, "style_wav": style_wav, "d_vector": d_vector}
def plot_outputs(self, text, wav, alignment, outputs):
figures = {}
pitch_avg_pred = outputs["pitch"].cpu()
energy_avg_pred = outputs["energy"].cpu()
spec = wav_to_mel(
y=torch.from_numpy(wav[None, :]),
n_fft=self.ap.fft_size,
sample_rate=self.ap.sample_rate,
num_mels=self.ap.num_mels,
hop_length=self.ap.hop_length,
win_length=self.ap.win_length,
fmin=self.ap.mel_fmin,
fmax=self.ap.mel_fmax,
center=False,
)[0].transpose(0, 1)
pitch = compute_f0(
x=wav[0],
sample_rate=self.ap.sample_rate,
hop_length=self.ap.hop_length,
pitch_fmax=self.ap.pitch_fmax,
)
input_text = self.tokenizer.ids_to_text(self.tokenizer.text_to_ids(text, language="en"))
input_text = input_text.replace("<BLNK>", "_")
durations = outputs["durations"]
pitch_avg = average_over_durations(torch.from_numpy(pitch)[None, None, :], durations.cpu()) # [1, 1, n_frames]
pitch_avg_pred_denorm = (pitch_avg_pred * self.pitch_std) + self.pitch_mean
figures["alignment"] = plot_alignment(alignment.transpose(1, 2), output_fig=False)
figures["spectrogram"] = plot_spectrogram(spec)
figures["pitch_from_wav"] = plot_pitch(pitch, spec)
figures["pitch_avg_from_wav"] = plot_avg_pitch(pitch_avg.squeeze(), input_text)
figures["pitch_avg_pred"] = plot_avg_pitch(pitch_avg_pred_denorm.squeeze(), input_text)
figures["energy_avg_pred"] = plot_avg_pitch(energy_avg_pred.squeeze(), input_text)
return figures
def synthesize(
self,
text: str,
speaker_id: str = None,
d_vector: torch.tensor = None,
pitch_transform=None,
**kwargs,
): # pylint: disable=unused-argument
# TODO: add cloning support with ref_waveform
is_cuda = next(self.parameters()).is_cuda
# convert text to sequence of token IDs
text_inputs = np.asarray(
self.tokenizer.text_to_ids(text, language=None),
dtype=np.int32,
)
# set speaker inputs
_speaker_id = None
if speaker_id is not None and self.args.use_speaker_embedding:
if isinstance(speaker_id, str) and self.args.use_speaker_embedding:
# get the speaker id for the speaker embedding layer
_speaker_id = self.speaker_manager.name_to_id[speaker_id]
_speaker_id = id_to_torch(_speaker_id, cuda=is_cuda)
if speaker_id is not None and self.args.use_d_vector_file:
# get the average d_vector for the speaker
d_vector = self.speaker_manager.get_mean_embedding(speaker_id, num_samples=None, randomize=False)
d_vector = embedding_to_torch(d_vector, cuda=is_cuda)
text_inputs = numpy_to_torch(text_inputs, torch.long, cuda=is_cuda)
text_inputs = text_inputs.unsqueeze(0)
# synthesize voice
outputs = self.inference(
text_inputs,
aux_input={"d_vectors": d_vector, "speaker_ids": _speaker_id},
pitch_transform=pitch_transform,
# energy_transform=energy_transform
)
# collect outputs
wav = outputs["model_outputs"][0].data.cpu().numpy()
alignments = outputs["alignments"]
return_dict = {
"wav": wav,
"alignments": alignments,
"text_inputs": text_inputs,
"outputs": outputs,
}
return return_dict
def synthesize_with_gl(self, text: str, speaker_id, d_vector):
is_cuda = next(self.parameters()).is_cuda
# convert text to sequence of token IDs
text_inputs = np.asarray(
self.tokenizer.text_to_ids(text, language=None),
dtype=np.int32,
)
# pass tensors to backend
if speaker_id is not None:
speaker_id = id_to_torch(speaker_id, cuda=is_cuda)
if d_vector is not None:
d_vector = embedding_to_torch(d_vector, cuda=is_cuda)
text_inputs = numpy_to_torch(text_inputs, torch.long, cuda=is_cuda)
text_inputs = text_inputs.unsqueeze(0)
# synthesize voice
outputs = self.inference_spec_decoder(
x=text_inputs,
aux_input={"d_vectors": d_vector, "speaker_ids": speaker_id},
)
# collect outputs
S = outputs["model_outputs"].cpu().numpy()[0].T
S = db_to_amp_numpy(x=S, gain=1, base=None)
wav = mel_to_wav_numpy(mel=S, mel_basis=self.mel_basis, **self.config.audio)
alignments = outputs["alignments"]
return_dict = {
"wav": wav[None, :],
"alignments": alignments,
"text_inputs": text_inputs,
"outputs": outputs,
}
return return_dict
@torch.no_grad()
def test_run(self, assets) -> Tuple[Dict, Dict]:
"""Generic test run for `tts` models used by `Trainer`.
You can override this for a different behaviour.
Returns:
Tuple[Dict, Dict]: Test figures and audios to be projected to Tensorboard.
"""
print(" | > Synthesizing test sentences.")
test_audios = {}
test_figures = {}
test_sentences = self.config.test_sentences
for idx, s_info in enumerate(test_sentences):
aux_inputs = self.get_aux_input_from_test_sentences(s_info)
outputs = self.synthesize(
aux_inputs["text"],
config=self.config,
speaker_id=aux_inputs["speaker_id"],
d_vector=aux_inputs["d_vector"],
)
outputs_gl = self.synthesize_with_gl(
aux_inputs["text"],
speaker_id=aux_inputs["speaker_id"],
d_vector=aux_inputs["d_vector"],
)
# speaker_name = self.speaker_manager.speaker_names[aux_inputs["speaker_id"]]
test_audios["{}-audio".format(idx)] = outputs["wav"].T
test_audios["{}-audio_encoder".format(idx)] = outputs_gl["wav"].T
test_figures["{}-alignment".format(idx)] = plot_alignment(outputs["alignments"], output_fig=False)
return {"figures": test_figures, "audios": test_audios}
def test_log(
self, outputs: dict, logger: "Logger", assets: dict, steps: int # pylint: disable=unused-argument
) -> None:
logger.test_audios(steps, outputs["audios"], self.config.audio.sample_rate)
logger.test_figures(steps, outputs["figures"])
def format_batch(self, batch: Dict) -> Dict:
"""Compute speaker, langugage IDs and d_vector for the batch if necessary."""
speaker_ids = None
d_vectors = None
# get numerical speaker ids from speaker names
if self.speaker_manager is not None and self.speaker_manager.speaker_names and self.args.use_speaker_embedding:
speaker_ids = [self.speaker_manager.name_to_id[sn] for sn in batch["speaker_names"]]
if speaker_ids is not None:
speaker_ids = torch.LongTensor(speaker_ids)
batch["speaker_ids"] = speaker_ids
# get d_vectors from audio file names
if self.speaker_manager is not None and self.speaker_manager.embeddings and self.args.use_d_vector_file:
d_vector_mapping = self.speaker_manager.embeddings
d_vectors = [d_vector_mapping[w]["embedding"] for w in batch["audio_unique_names"]]
d_vectors = torch.FloatTensor(d_vectors)
batch["d_vectors"] = d_vectors
batch["speaker_ids"] = speaker_ids
return batch
def format_batch_on_device(self, batch):
"""Compute spectrograms on the device."""
ac = self.ap
# compute spectrograms
batch["mel_input"] = wav_to_mel(
batch["waveform"],
hop_length=ac.hop_length,
win_length=ac.win_length,
n_fft=ac.fft_size,
num_mels=ac.num_mels,
sample_rate=ac.sample_rate,
fmin=ac.mel_fmin,
fmax=ac.mel_fmax,
center=False,
)
# TODO: Align pitch properly
# assert (
# batch["pitch"].shape[2] == batch["mel_input"].shape[2]
# ), f"{batch['pitch'].shape[2]}, {batch['mel_input'].shape[2]}"
batch["pitch"] = batch["pitch"][:, :, : batch["mel_input"].shape[2]] if batch["pitch"] is not None else None
batch["mel_lengths"] = (batch["mel_input"].shape[2] * batch["waveform_rel_lens"]).int()
# zero the padding frames
batch["mel_input"] = batch["mel_input"] * sequence_mask(batch["mel_lengths"]).unsqueeze(1)
# format attn priors as we now the max mel length
# TODO: fix 1 diff b/w mel_lengths and attn_priors
if self.config.use_attn_priors:
attn_priors_np = batch["attn_priors"]
batch["attn_priors"] = torch.zeros(
batch["mel_input"].shape[0],
batch["mel_lengths"].max(),
batch["text_lengths"].max(),
device=batch["mel_input"].device,
)
for i in range(batch["mel_input"].shape[0]):
batch["attn_priors"][i, : attn_priors_np[i].shape[0], : attn_priors_np[i].shape[1]] = torch.from_numpy(
attn_priors_np[i]
)
batch["energy"] = None
batch["energy"] = wav_to_energy( # [B, 1, T_max2]
batch["waveform"],
hop_length=ac.hop_length,
win_length=ac.win_length,
n_fft=ac.fft_size,
center=False,
)
batch["energy"] = self.energy_scaler(batch["energy"])
return batch
def get_sampler(self, config: Coqpit, dataset: TTSDataset, num_gpus=1):
weights = None
data_items = dataset.samples
if getattr(config, "use_weighted_sampler", False):
for attr_name, alpha in config.weighted_sampler_attrs.items():
print(f" > Using weighted sampler for attribute '{attr_name}' with alpha '{alpha}'")
multi_dict = config.weighted_sampler_multipliers.get(attr_name, None)
print(multi_dict)
weights, attr_names, attr_weights = get_attribute_balancer_weights(
attr_name=attr_name, items=data_items, multi_dict=multi_dict
)
weights = weights * alpha
print(f" > Attribute weights for '{attr_names}' \n | > {attr_weights}")
if weights is not None:
sampler = WeightedRandomSampler(weights, len(weights))
else:
sampler = None
# sampler for DDP
if sampler is None:
sampler = DistributedSampler(dataset) if num_gpus > 1 else None
else: # If a sampler is already defined use this sampler and DDP sampler together
sampler = DistributedSamplerWrapper(sampler) if num_gpus > 1 else sampler
return sampler
def get_data_loader(
self,
config: Coqpit,
assets: Dict,
is_eval: bool,
samples: Union[List[Dict], List[List]],
verbose: bool,
num_gpus: int,
rank: int = None,
) -> "DataLoader":
if is_eval and not config.run_eval:
loader = None
else:
# init dataloader
dataset = ForwardTTSE2eDataset(
samples=samples,
ap=self.ap,
batch_group_size=0 if is_eval else config.batch_group_size * config.batch_size,
min_text_len=config.min_text_len,
max_text_len=config.max_text_len,
min_audio_len=config.min_audio_len,
max_audio_len=config.max_audio_len,
phoneme_cache_path=config.phoneme_cache_path,
precompute_num_workers=config.precompute_num_workers,
compute_f0=config.compute_f0,
f0_cache_path=config.f0_cache_path,
attn_prior_cache_path=config.attn_prior_cache_path if config.use_attn_priors else None,
verbose=verbose,
tokenizer=self.tokenizer,
start_by_longest=config.start_by_longest,
)
# wait all the DDP process to be ready
if num_gpus > 1:
dist.barrier()
# sort input sequences ascendingly by length
dataset.preprocess_samples()
# get samplers
sampler = self.get_sampler(config, dataset, num_gpus)
loader = DataLoader(
dataset,
batch_size=config.eval_batch_size if is_eval else config.batch_size,
shuffle=False, # shuffle is done in the dataset.
drop_last=False, # setting this False might cause issues in AMP training.
sampler=sampler,
collate_fn=dataset.collate_fn,
num_workers=config.num_eval_loader_workers if is_eval else config.num_loader_workers,
pin_memory=True,
)
# get pitch mean and std
self.pitch_mean = dataset.f0_dataset.mean
self.pitch_std = dataset.f0_dataset.std
return loader
def get_criterion(self):
return [VitsDiscriminatorLoss(self.config), DelightfulTTSLoss(self.config)]
def get_optimizer(self) -> List:
"""Initiate and return the GAN optimizers based on the config parameters.
It returnes 2 optimizers in a list. First one is for the generator and the second one is for the discriminator.
Returns:
List: optimizers.
"""
optimizer_disc = get_optimizer(
self.config.optimizer, self.config.optimizer_params, self.config.lr_disc, self.disc
)
gen_parameters = chain(params for k, params in self.named_parameters() if not k.startswith("disc."))
optimizer_gen = get_optimizer(
self.config.optimizer, self.config.optimizer_params, self.config.lr_gen, parameters=gen_parameters
)
return [optimizer_disc, optimizer_gen]
def get_lr(self) -> List:
"""Set the initial learning rates for each optimizer.
Returns:
List: learning rates for each optimizer.
"""
return [self.config.lr_disc, self.config.lr_gen]
def get_scheduler(self, optimizer) -> List:
"""Set the schedulers for each optimizer.
Args:
optimizer (List[`torch.optim.Optimizer`]): List of optimizers.
Returns:
List: Schedulers, one for each optimizer.
"""
scheduler_D = get_scheduler(self.config.lr_scheduler_gen, self.config.lr_scheduler_gen_params, optimizer[0])
scheduler_G = get_scheduler(self.config.lr_scheduler_disc, self.config.lr_scheduler_disc_params, optimizer[1])
return [scheduler_D, scheduler_G]
def on_epoch_end(self, trainer): # pylint: disable=unused-argument
# stop updating mean and var
# TODO: do the same for F0
self.energy_scaler.eval()
@staticmethod
def init_from_config(
config: "DelightfulTTSConfig", samples: Union[List[List], List[Dict]] = None, verbose=False
): # pylint: disable=unused-argument
"""Initiate model from config
Args:
config (ForwardTTSE2eConfig): Model config.
samples (Union[List[List], List[Dict]]): Training samples to parse speaker ids for training.
Defaults to None.
"""
tokenizer, new_config = TTSTokenizer.init_from_config(config)
speaker_manager = SpeakerManager.init_from_config(config.model_args, samples)
ap = AudioProcessor.init_from_config(config=config)
return DelightfulTTS(config=new_config, tokenizer=tokenizer, speaker_manager=speaker_manager, ap=ap)
def load_checkpoint(self, config, checkpoint_path, eval=False):
"""Load model from a checkpoint created by the 👟"""
# pylint: disable=unused-argument, redefined-builtin
state = load_fsspec(checkpoint_path, map_location=torch.device("cpu"))
self.load_state_dict(state["model"])
if eval:
self.eval()
assert not self.training
def get_state_dict(self):
"""Custom state dict of the model with all the necessary components for inference."""
save_state = {"config": self.config.to_dict(), "args": self.args.to_dict(), "model": self.state_dict}
if hasattr(self, "emb_g"):
save_state["speaker_ids"] = self.speaker_manager.speaker_names
if self.args.use_d_vector_file:
# TODO: implement saving of d_vectors
...
return save_state
def save(self, config, checkpoint_path):
"""Save model to a file."""
save_state = self.get_state_dict(config, checkpoint_path) # pylint: disable=too-many-function-args
save_state["pitch_mean"] = self.pitch_mean
save_state["pitch_std"] = self.pitch_std
torch.save(save_state, checkpoint_path)
def on_train_step_start(self, trainer) -> None:
"""Enable the discriminator training based on `steps_to_start_discriminator`
Args:
trainer (Trainer): Trainer object.
"""
self.binary_loss_weight = min(trainer.epochs_done / self.config.binary_loss_warmup_epochs, 1.0) * 1.0
self.train_disc = ( # pylint: disable=attribute-defined-outside-init
trainer.total_steps_done >= self.config.steps_to_start_discriminator
)
class DelightfulTTSLoss(nn.Module):
def __init__(self, config):
super().__init__()
self.mse_loss = nn.MSELoss()
self.mae_loss = nn.L1Loss()
self.forward_sum_loss = ForwardSumLoss()
self.multi_scale_stft_loss = MultiScaleSTFTLoss(**config.multi_scale_stft_loss_params)
self.mel_loss_alpha = config.mel_loss_alpha
self.aligner_loss_alpha = config.aligner_loss_alpha
self.pitch_loss_alpha = config.pitch_loss_alpha
self.energy_loss_alpha = config.energy_loss_alpha
self.u_prosody_loss_alpha = config.u_prosody_loss_alpha
self.p_prosody_loss_alpha = config.p_prosody_loss_alpha
self.dur_loss_alpha = config.dur_loss_alpha
self.char_dur_loss_alpha = config.char_dur_loss_alpha
self.binary_alignment_loss_alpha = config.binary_align_loss_alpha
self.vocoder_mel_loss_alpha = config.vocoder_mel_loss_alpha
self.feat_loss_alpha = config.feat_loss_alpha
self.gen_loss_alpha = config.gen_loss_alpha
self.multi_scale_stft_loss_alpha = config.multi_scale_stft_loss_alpha
@staticmethod
def _binary_alignment_loss(alignment_hard, alignment_soft):
"""Binary loss that forces soft alignments to match the hard alignments as
explained in `https://arxiv.org/pdf/2108.10447.pdf`.
"""
log_sum = torch.log(torch.clamp(alignment_soft[alignment_hard == 1], min=1e-12)).sum()
return -log_sum / alignment_hard.sum()
@staticmethod
def feature_loss(feats_real, feats_generated):
loss = 0
for dr, dg in zip(feats_real, feats_generated):
for rl, gl in zip(dr, dg):
rl = rl.float().detach()
gl = gl.float()
loss += torch.mean(torch.abs(rl - gl))
return loss * 2
@staticmethod
def generator_loss(scores_fake):
loss = 0
gen_losses = []
for dg in scores_fake:
dg = dg.float()
l = torch.mean((1 - dg) ** 2)
gen_losses.append(l)
loss += l
return loss, gen_losses
def forward(
self,
mel_output,
mel_target,
mel_lens,
dur_output,
dur_target,
pitch_output,
pitch_target,
energy_output,
energy_target,
src_lens,
waveform,
waveform_hat,
p_prosody_ref,
p_prosody_pred,
u_prosody_ref,
u_prosody_pred,
aligner_logprob,
aligner_hard,
aligner_soft,
binary_loss_weight=None,
feats_fake=None,
feats_real=None,
scores_fake=None,
spec_slice=None,
spec_slice_hat=None,
skip_disc=False,
):
"""
Shapes:
- mel_output: :math:`(B, C_mel, T_mel)`
- mel_target: :math:`(B, C_mel, T_mel)`
- mel_lens: :math:`(B)`
- dur_output: :math:`(B, T_src)`
- dur_target: :math:`(B, T_src)`
- pitch_output: :math:`(B, 1, T_src)`
- pitch_target: :math:`(B, 1, T_src)`
- energy_output: :math:`(B, 1, T_src)`
- energy_target: :math:`(B, 1, T_src)`
- src_lens: :math:`(B)`
- waveform: :math:`(B, 1, T_wav)`
- waveform_hat: :math:`(B, 1, T_wav)`
- p_prosody_ref: :math:`(B, T_src, 4)`
- p_prosody_pred: :math:`(B, T_src, 4)`
- u_prosody_ref: :math:`(B, 1, 256)
- u_prosody_pred: :math:`(B, 1, 256)
- aligner_logprob: :math:`(B, 1, T_mel, T_src)`
- aligner_hard: :math:`(B, T_mel, T_src)`
- aligner_soft: :math:`(B, T_mel, T_src)`
- spec_slice: :math:`(B, C_mel, T_mel)`
- spec_slice_hat: :math:`(B, C_mel, T_mel)`
"""
loss_dict = {}
src_mask = sequence_mask(src_lens).to(mel_output.device) # (B, T_src)
mel_mask = sequence_mask(mel_lens).to(mel_output.device) # (B, T_mel)
dur_target.requires_grad = False
mel_target.requires_grad = False
pitch_target.requires_grad = False
masked_mel_predictions = mel_output.masked_select(mel_mask[:, None])
mel_targets = mel_target.masked_select(mel_mask[:, None])
mel_loss = self.mae_loss(masked_mel_predictions, mel_targets)
p_prosody_ref = p_prosody_ref.detach()
p_prosody_loss = 0.5 * self.mae_loss(
p_prosody_ref.masked_select(src_mask.unsqueeze(-1)),
p_prosody_pred.masked_select(src_mask.unsqueeze(-1)),
)
u_prosody_ref = u_prosody_ref.detach()
u_prosody_loss = 0.5 * self.mae_loss(u_prosody_ref, u_prosody_pred)
duration_loss = self.mse_loss(dur_output, dur_target)
pitch_output = pitch_output.masked_select(src_mask[:, None])
pitch_target = pitch_target.masked_select(src_mask[:, None])
pitch_loss = self.mse_loss(pitch_output, pitch_target)
energy_output = energy_output.masked_select(src_mask[:, None])
energy_target = energy_target.masked_select(src_mask[:, None])
energy_loss = self.mse_loss(energy_output, energy_target)
forward_sum_loss = self.forward_sum_loss(aligner_logprob, src_lens, mel_lens)
total_loss = (
(mel_loss * self.mel_loss_alpha)
+ (duration_loss * self.dur_loss_alpha)
+ (u_prosody_loss * self.u_prosody_loss_alpha)
+ (p_prosody_loss * self.p_prosody_loss_alpha)
+ (pitch_loss * self.pitch_loss_alpha)
+ (energy_loss * self.energy_loss_alpha)
+ (forward_sum_loss * self.aligner_loss_alpha)
)
if self.binary_alignment_loss_alpha > 0 and aligner_hard is not None:
binary_alignment_loss = self._binary_alignment_loss(aligner_hard, aligner_soft)
total_loss = total_loss + self.binary_alignment_loss_alpha * binary_alignment_loss * binary_loss_weight
if binary_loss_weight:
loss_dict["loss_binary_alignment"] = (
self.binary_alignment_loss_alpha * binary_alignment_loss * binary_loss_weight
)
else:
loss_dict["loss_binary_alignment"] = self.binary_alignment_loss_alpha * binary_alignment_loss
loss_dict["loss_aligner"] = self.aligner_loss_alpha * forward_sum_loss
loss_dict["loss_mel"] = self.mel_loss_alpha * mel_loss
loss_dict["loss_duration"] = self.dur_loss_alpha * duration_loss
loss_dict["loss_u_prosody"] = self.u_prosody_loss_alpha * u_prosody_loss
loss_dict["loss_p_prosody"] = self.p_prosody_loss_alpha * p_prosody_loss
loss_dict["loss_pitch"] = self.pitch_loss_alpha * pitch_loss
loss_dict["loss_energy"] = self.energy_loss_alpha * energy_loss
loss_dict["loss"] = total_loss
# vocoder losses
if not skip_disc:
loss_feat = self.feature_loss(feats_real=feats_real, feats_generated=feats_fake) * self.feat_loss_alpha
loss_gen = self.generator_loss(scores_fake=scores_fake)[0] * self.gen_loss_alpha
loss_dict["vocoder_loss_feat"] = loss_feat
loss_dict["vocoder_loss_gen"] = loss_gen
loss_dict["loss"] = loss_dict["loss"] + loss_feat + loss_gen
loss_mel = torch.nn.functional.l1_loss(spec_slice, spec_slice_hat) * self.vocoder_mel_loss_alpha
loss_stft_mg, loss_stft_sc = self.multi_scale_stft_loss(y_hat=waveform_hat, y=waveform)
loss_stft_mg = loss_stft_mg * self.multi_scale_stft_loss_alpha
loss_stft_sc = loss_stft_sc * self.multi_scale_stft_loss_alpha
loss_dict["vocoder_loss_mel"] = loss_mel
loss_dict["vocoder_loss_stft_mg"] = loss_stft_mg
loss_dict["vocoder_loss_stft_sc"] = loss_stft_sc
loss_dict["loss"] = loss_dict["loss"] + loss_mel + loss_stft_sc + loss_stft_mg
return loss_dict
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/include/fst/script/map.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_SCRIPT_MAP_H_
#define FST_SCRIPT_MAP_H_
#include <memory>
#include <tuple>
#include <fst/arc-map.h>
#include <fst/state-map.h>
#include <fst/script/arg-packs.h>
#include <fst/script/fst-class.h>
#include <fst/script/weight-class.h>
namespace fst {
namespace script {
template <class M>
Fst<typename M::ToArc> *ArcMap(const Fst<typename M::FromArc> &fst,
const M &mapper) {
using ToArc = typename M::ToArc;
auto *ofst = new VectorFst<ToArc>;
ArcMap(fst, ofst, mapper);
return ofst;
}
template <class M>
Fst<typename M::ToArc> *StateMap(const Fst<typename M::FromArc> &fst,
const M &mapper) {
using ToArc = typename M::ToArc;
auto *ofst = new VectorFst<ToArc>;
StateMap(fst, ofst, mapper);
return ofst;
}
enum MapType {
ARC_SUM_MAPPER,
ARC_UNIQUE_MAPPER,
IDENTITY_MAPPER,
INPUT_EPSILON_MAPPER,
INVERT_MAPPER,
OUTPUT_EPSILON_MAPPER,
PLUS_MAPPER,
POWER_MAPPER,
QUANTIZE_MAPPER,
RMWEIGHT_MAPPER,
SUPERFINAL_MAPPER,
TIMES_MAPPER,
TO_LOG_MAPPER,
TO_LOG64_MAPPER,
TO_STD_MAPPER
};
using MapInnerArgs =
std::tuple<const FstClass &, MapType, float, double, const WeightClass &>;
using MapArgs = WithReturnValue<FstClass *, MapInnerArgs>;
template <class Arc>
void Map(MapArgs *args) {
using Weight = typename Arc::Weight;
const Fst<Arc> &ifst = *(std::get<0>(args->args).GetFst<Arc>());
const auto map_type = std::get<1>(args->args);
switch (map_type) {
case ARC_SUM_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(StateMap(ifst, ArcSumMapper<Arc>(ifst)));
args->retval = new FstClass(*ofst);
return;
}
case ARC_UNIQUE_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(
StateMap(ifst, ArcUniqueMapper<Arc>(ifst)));
args->retval = new FstClass(*ofst);
return;
}
case IDENTITY_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, IdentityArcMapper<Arc>()));
args->retval = new FstClass(*ofst);
return;
}
case INPUT_EPSILON_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, InputEpsilonMapper<Arc>()));
args->retval = new FstClass(*ofst);
return;
}
case INVERT_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, InvertWeightMapper<Arc>()));
args->retval = new FstClass(*ofst);
return;
}
case OUTPUT_EPSILON_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, OutputEpsilonMapper<Arc>()));
args->retval = new FstClass(*ofst);
return;
}
case PLUS_MAPPER: {
const auto weight = *(std::get<4>(args->args).GetWeight<Weight>());
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, PlusMapper<Arc>(weight)));
args->retval = new FstClass(*ofst);
return;
}
case POWER_MAPPER: {
const auto power = std::get<3>(args->args);
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, PowerMapper<Arc>(power)));
args->retval = new FstClass(*ofst);
return;
}
case QUANTIZE_MAPPER: {
const auto delta = std::get<2>(args->args);
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, QuantizeMapper<Arc>(delta)));
args->retval = new FstClass(*ofst);
return;
}
case RMWEIGHT_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, RmWeightMapper<Arc>()));
args->retval = new FstClass(*ofst);
return;
}
case SUPERFINAL_MAPPER: {
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, SuperFinalMapper<Arc>()));
args->retval = new FstClass(*ofst);
return;
}
case TIMES_MAPPER: {
const auto weight = *(std::get<4>(args->args).GetWeight<Weight>());
std::unique_ptr<Fst<Arc>> ofst(ArcMap(ifst, TimesMapper<Arc>(weight)));
args->retval = new FstClass(*ofst);
return;
}
case TO_LOG_MAPPER: {
std::unique_ptr<Fst<LogArc>> ofst(
ArcMap(ifst, WeightConvertMapper<Arc, LogArc>()));
args->retval = new FstClass(*ofst);
return;
}
case TO_LOG64_MAPPER: {
std::unique_ptr<Fst<Log64Arc>> ofst(
ArcMap(ifst, WeightConvertMapper<Arc, Log64Arc>()));
args->retval = new FstClass(*ofst);
return;
}
case TO_STD_MAPPER: {
std::unique_ptr<Fst<StdArc>> ofst(
ArcMap(ifst, WeightConvertMapper<Arc, StdArc>()));
args->retval = new FstClass(*ofst);
return;
}
}
}
FstClass *Map(const FstClass &ifst, MapType map_type, float delta, double power,
const WeightClass &weight);
} // namespace script
} // namespace fst
#endif // FST_SCRIPT_MAP_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/lib/fst.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// FST definitions.
#include <fst/fst.h>
#include <sstream>
#include <fst/flags.h>
#include <fst/log.h>
#include <fst/matcher-fst.h> // declarations of *_lookahead_fst_type
// FST flag definitions.
DEFINE_bool(fst_verify_properties, false,
"Verify FST properties queried by TestProperties");
DEFINE_bool(fst_default_cache_gc, true, "Enable garbage collection of cache");
DEFINE_int64_t(fst_default_cache_gc_limit, 1 << 20LL,
"Cache byte size that triggers garbage collection");
DEFINE_bool(fst_align, false, "Write FST data aligned where appropriate");
DEFINE_string(save_relabel_ipairs, "", "Save input relabel pairs to file");
DEFINE_string(save_relabel_opairs, "", "Save output relabel pairs to file");
DEFINE_string(fst_read_mode, "read",
"Default file reading mode for mappable files");
namespace fst {
// FST type definitions for lookahead FSTs.
const char arc_lookahead_fst_type[] = "arc_lookahead";
const char ilabel_lookahead_fst_type[] = "ilabel_lookahead";
const char olabel_lookahead_fst_type[] = "olabel_lookahead";
// Identifies stream data as an FST (and its endianity).
constexpr int32_t kFstMagicNumber = 2125659606;
// Checks for FST magic number in stream, to indicate caller function that the
// stream content is an FST header.
bool IsFstHeader(std::istream &strm, const string &source) {
int64_t pos = strm.tellg();
bool match = true;
int32_t magic_number = 0;
ReadType(strm, &magic_number);
if (magic_number != kFstMagicNumber) {
match = false;
}
strm.seekg(pos);
return match;
}
// Checks FST magic number and reads in the header; if rewind = true,
// the stream is repositioned before call if possible.
bool FstHeader::Read(std::istream &strm, const string &source, bool rewind) {
int64_t pos = 0;
if (rewind) pos = strm.tellg();
int32_t magic_number = 0;
ReadType(strm, &magic_number);
if (magic_number != kFstMagicNumber) {
LOG(ERROR) << "FstHeader::Read: Bad FST header: " << source;
if (rewind) strm.seekg(pos);
return false;
}
ReadType(strm, &fsttype_);
ReadType(strm, &arctype_);
ReadType(strm, &version_);
ReadType(strm, &flags_);
ReadType(strm, &properties_);
ReadType(strm, &start_);
ReadType(strm, &numstates_);
ReadType(strm, &numarcs_);
if (!strm) {
LOG(ERROR) << "FstHeader::Read: Read failed: " << source;
return false;
}
if (rewind) strm.seekg(pos);
return true;
}
// Writes FST magic number and FST header.
bool FstHeader::Write(std::ostream &strm, const string &source) const {
WriteType(strm, kFstMagicNumber);
WriteType(strm, fsttype_);
WriteType(strm, arctype_);
WriteType(strm, version_);
WriteType(strm, flags_);
WriteType(strm, properties_);
WriteType(strm, start_);
WriteType(strm, numstates_);
WriteType(strm, numarcs_);
return true;
}
string FstHeader::DebugString() const {
std::ostringstream ostrm;
ostrm << "fsttype: \"" << fsttype_ << "\" arctype: \"" << arctype_
<< "\" version: \"" << version_ << "\" flags: \"" << flags_
<< "\" properties: \"" << properties_ << "\" start: \"" << start_
<< "\" numstates: \"" << numstates_ << "\" numarcs: \"" << numarcs_
<< "\"";
return ostrm.str();
}
FstReadOptions::FstReadOptions(const string &source, const FstHeader *header,
const SymbolTable *isymbols,
const SymbolTable *osymbols)
: source(source),
header(header),
isymbols(isymbols),
osymbols(osymbols),
read_isymbols(true),
read_osymbols(true) {
mode = ReadMode(FLAGS_fst_read_mode);
}
FstReadOptions::FstReadOptions(const string &source,
const SymbolTable *isymbols,
const SymbolTable *osymbols)
: source(source),
header(nullptr),
isymbols(isymbols),
osymbols(osymbols),
read_isymbols(true),
read_osymbols(true) {
mode = ReadMode(FLAGS_fst_read_mode);
}
FstReadOptions::FileReadMode FstReadOptions::ReadMode(const string &mode) {
if (mode == "read") return READ;
if (mode == "map") return MAP;
LOG(ERROR) << "Unknown file read mode " << mode;
return READ;
}
string FstReadOptions::DebugString() const {
std::ostringstream ostrm;
ostrm << "source: \"" << source << "\" mode: \""
<< (mode == READ ? "READ" : "MAP") << "\" read_isymbols: \""
<< (read_isymbols ? "true" : "false") << "\" read_osymbols: \""
<< (read_osymbols ? "true" : "false") << "\" header: \""
<< (header ? "set" : "null") << "\" isymbols: \""
<< (isymbols ? "set" : "null") << "\" osymbols: \""
<< (osymbols ? "set" : "null") << "\"";
return ostrm.str();
}
} // namespace fst
| 0 |
coqui_public_repos/TTS/TTS | coqui_public_repos/TTS/TTS/bin/synthesize.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import contextlib
import sys
from argparse import RawTextHelpFormatter
# pylint: disable=redefined-outer-name, unused-argument
from pathlib import Path
description = """
Synthesize speech on command line.
You can either use your trained model or choose a model from the provided list.
If you don't specify any models, then it uses LJSpeech based English model.
#### Single Speaker Models
- List provided models:
```
$ tts --list_models
```
- Get model info (for both tts_models and vocoder_models):
- Query by type/name:
The model_info_by_name uses the name as it from the --list_models.
```
$ tts --model_info_by_name "<model_type>/<language>/<dataset>/<model_name>"
```
For example:
```
$ tts --model_info_by_name tts_models/tr/common-voice/glow-tts
$ tts --model_info_by_name vocoder_models/en/ljspeech/hifigan_v2
```
- Query by type/idx:
The model_query_idx uses the corresponding idx from --list_models.
```
$ tts --model_info_by_idx "<model_type>/<model_query_idx>"
```
For example:
```
$ tts --model_info_by_idx tts_models/3
```
- Query info for model info by full name:
```
$ tts --model_info_by_name "<model_type>/<language>/<dataset>/<model_name>"
```
- Run TTS with default models:
```
$ tts --text "Text for TTS" --out_path output/path/speech.wav
```
- Run TTS and pipe out the generated TTS wav file data:
```
$ tts --text "Text for TTS" --pipe_out --out_path output/path/speech.wav | aplay
```
- Run a TTS model with its default vocoder model:
```
$ tts --text "Text for TTS" --model_name "<model_type>/<language>/<dataset>/<model_name>" --out_path output/path/speech.wav
```
For example:
```
$ tts --text "Text for TTS" --model_name "tts_models/en/ljspeech/glow-tts" --out_path output/path/speech.wav
```
- Run with specific TTS and vocoder models from the list:
```
$ tts --text "Text for TTS" --model_name "<model_type>/<language>/<dataset>/<model_name>" --vocoder_name "<model_type>/<language>/<dataset>/<model_name>" --out_path output/path/speech.wav
```
For example:
```
$ tts --text "Text for TTS" --model_name "tts_models/en/ljspeech/glow-tts" --vocoder_name "vocoder_models/en/ljspeech/univnet" --out_path output/path/speech.wav
```
- Run your own TTS model (Using Griffin-Lim Vocoder):
```
$ tts --text "Text for TTS" --model_path path/to/model.pth --config_path path/to/config.json --out_path output/path/speech.wav
```
- Run your own TTS and Vocoder models:
```
$ tts --text "Text for TTS" --model_path path/to/model.pth --config_path path/to/config.json --out_path output/path/speech.wav
--vocoder_path path/to/vocoder.pth --vocoder_config_path path/to/vocoder_config.json
```
#### Multi-speaker Models
- List the available speakers and choose a <speaker_id> among them:
```
$ tts --model_name "<language>/<dataset>/<model_name>" --list_speaker_idxs
```
- Run the multi-speaker TTS model with the target speaker ID:
```
$ tts --text "Text for TTS." --out_path output/path/speech.wav --model_name "<language>/<dataset>/<model_name>" --speaker_idx <speaker_id>
```
- Run your own multi-speaker TTS model:
```
$ tts --text "Text for TTS" --out_path output/path/speech.wav --model_path path/to/model.pth --config_path path/to/config.json --speakers_file_path path/to/speaker.json --speaker_idx <speaker_id>
```
### Voice Conversion Models
```
$ tts --out_path output/path/speech.wav --model_name "<language>/<dataset>/<model_name>" --source_wav <path/to/speaker/wav> --target_wav <path/to/reference/wav>
```
"""
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
if v.lower() in ("no", "false", "f", "n", "0"):
return False
raise argparse.ArgumentTypeError("Boolean value expected.")
def main():
parser = argparse.ArgumentParser(
description=description.replace(" ```\n", ""),
formatter_class=RawTextHelpFormatter,
)
parser.add_argument(
"--list_models",
type=str2bool,
nargs="?",
const=True,
default=False,
help="list available pre-trained TTS and vocoder models.",
)
parser.add_argument(
"--model_info_by_idx",
type=str,
default=None,
help="model info using query format: <model_type>/<model_query_idx>",
)
parser.add_argument(
"--model_info_by_name",
type=str,
default=None,
help="model info using query format: <model_type>/<language>/<dataset>/<model_name>",
)
parser.add_argument("--text", type=str, default=None, help="Text to generate speech.")
# Args for running pre-trained TTS models.
parser.add_argument(
"--model_name",
type=str,
default="tts_models/en/ljspeech/tacotron2-DDC",
help="Name of one of the pre-trained TTS models in format <language>/<dataset>/<model_name>",
)
parser.add_argument(
"--vocoder_name",
type=str,
default=None,
help="Name of one of the pre-trained vocoder models in format <language>/<dataset>/<model_name>",
)
# Args for running custom models
parser.add_argument("--config_path", default=None, type=str, help="Path to model config file.")
parser.add_argument(
"--model_path",
type=str,
default=None,
help="Path to model file.",
)
parser.add_argument(
"--out_path",
type=str,
default="tts_output.wav",
help="Output wav file path.",
)
parser.add_argument("--use_cuda", type=bool, help="Run model on CUDA.", default=False)
parser.add_argument("--device", type=str, help="Device to run model on.", default="cpu")
parser.add_argument(
"--vocoder_path",
type=str,
help="Path to vocoder model file. If it is not defined, model uses GL as vocoder. Please make sure that you installed vocoder library before (WaveRNN).",
default=None,
)
parser.add_argument("--vocoder_config_path", type=str, help="Path to vocoder model config file.", default=None)
parser.add_argument(
"--encoder_path",
type=str,
help="Path to speaker encoder model file.",
default=None,
)
parser.add_argument("--encoder_config_path", type=str, help="Path to speaker encoder config file.", default=None)
parser.add_argument(
"--pipe_out",
help="stdout the generated TTS wav file for shell pipe.",
type=str2bool,
nargs="?",
const=True,
default=False,
)
# args for multi-speaker synthesis
parser.add_argument("--speakers_file_path", type=str, help="JSON file for multi-speaker model.", default=None)
parser.add_argument("--language_ids_file_path", type=str, help="JSON file for multi-lingual model.", default=None)
parser.add_argument(
"--speaker_idx",
type=str,
help="Target speaker ID for a multi-speaker TTS model.",
default=None,
)
parser.add_argument(
"--language_idx",
type=str,
help="Target language ID for a multi-lingual TTS model.",
default=None,
)
parser.add_argument(
"--speaker_wav",
nargs="+",
help="wav file(s) to condition a multi-speaker TTS model with a Speaker Encoder. You can give multiple file paths. The d_vectors is computed as their average.",
default=None,
)
parser.add_argument("--gst_style", help="Wav path file for GST style reference.", default=None)
parser.add_argument(
"--capacitron_style_wav", type=str, help="Wav path file for Capacitron prosody reference.", default=None
)
parser.add_argument("--capacitron_style_text", type=str, help="Transcription of the reference.", default=None)
parser.add_argument(
"--list_speaker_idxs",
help="List available speaker ids for the defined multi-speaker model.",
type=str2bool,
nargs="?",
const=True,
default=False,
)
parser.add_argument(
"--list_language_idxs",
help="List available language ids for the defined multi-lingual model.",
type=str2bool,
nargs="?",
const=True,
default=False,
)
# aux args
parser.add_argument(
"--save_spectogram",
type=bool,
help="If true save raw spectogram for further (vocoder) processing in out_path.",
default=False,
)
parser.add_argument(
"--reference_wav",
type=str,
help="Reference wav file to convert in the voice of the speaker_idx or speaker_wav",
default=None,
)
parser.add_argument(
"--reference_speaker_idx",
type=str,
help="speaker ID of the reference_wav speaker (If not provided the embedding will be computed using the Speaker Encoder).",
default=None,
)
parser.add_argument(
"--progress_bar",
type=str2bool,
help="If true shows a progress bar for the model download. Defaults to True",
default=True,
)
# voice conversion args
parser.add_argument(
"--source_wav",
type=str,
default=None,
help="Original audio file to convert in the voice of the target_wav",
)
parser.add_argument(
"--target_wav",
type=str,
default=None,
help="Target audio file to convert in the voice of the source_wav",
)
parser.add_argument(
"--voice_dir",
type=str,
default=None,
help="Voice dir for tortoise model",
)
args = parser.parse_args()
# print the description if either text or list_models is not set
check_args = [
args.text,
args.list_models,
args.list_speaker_idxs,
args.list_language_idxs,
args.reference_wav,
args.model_info_by_idx,
args.model_info_by_name,
args.source_wav,
args.target_wav,
]
if not any(check_args):
parser.parse_args(["-h"])
pipe_out = sys.stdout if args.pipe_out else None
with contextlib.redirect_stdout(None if args.pipe_out else sys.stdout):
# Late-import to make things load faster
from TTS.api import TTS
from TTS.utils.manage import ModelManager
from TTS.utils.synthesizer import Synthesizer
# load model manager
path = Path(__file__).parent / "../.models.json"
manager = ModelManager(path, progress_bar=args.progress_bar)
api = TTS()
tts_path = None
tts_config_path = None
speakers_file_path = None
language_ids_file_path = None
vocoder_path = None
vocoder_config_path = None
encoder_path = None
encoder_config_path = None
vc_path = None
vc_config_path = None
model_dir = None
# CASE1 #list : list pre-trained TTS models
if args.list_models:
manager.list_models()
sys.exit()
# CASE2 #info : model info for pre-trained TTS models
if args.model_info_by_idx:
model_query = args.model_info_by_idx
manager.model_info_by_idx(model_query)
sys.exit()
if args.model_info_by_name:
model_query_full_name = args.model_info_by_name
manager.model_info_by_full_name(model_query_full_name)
sys.exit()
# CASE3: load pre-trained model paths
if args.model_name is not None and not args.model_path:
model_path, config_path, model_item = manager.download_model(args.model_name)
# tts model
if model_item["model_type"] == "tts_models":
tts_path = model_path
tts_config_path = config_path
if "default_vocoder" in model_item:
args.vocoder_name = (
model_item["default_vocoder"] if args.vocoder_name is None else args.vocoder_name
)
# voice conversion model
if model_item["model_type"] == "voice_conversion_models":
vc_path = model_path
vc_config_path = config_path
# tts model with multiple files to be loaded from the directory path
if model_item.get("author", None) == "fairseq" or isinstance(model_item["model_url"], list):
model_dir = model_path
tts_path = None
tts_config_path = None
args.vocoder_name = None
# load vocoder
if args.vocoder_name is not None and not args.vocoder_path:
vocoder_path, vocoder_config_path, _ = manager.download_model(args.vocoder_name)
# CASE4: set custom model paths
if args.model_path is not None:
tts_path = args.model_path
tts_config_path = args.config_path
speakers_file_path = args.speakers_file_path
language_ids_file_path = args.language_ids_file_path
if args.vocoder_path is not None:
vocoder_path = args.vocoder_path
vocoder_config_path = args.vocoder_config_path
if args.encoder_path is not None:
encoder_path = args.encoder_path
encoder_config_path = args.encoder_config_path
device = args.device
if args.use_cuda:
device = "cuda"
# load models
synthesizer = Synthesizer(
tts_path,
tts_config_path,
speakers_file_path,
language_ids_file_path,
vocoder_path,
vocoder_config_path,
encoder_path,
encoder_config_path,
vc_path,
vc_config_path,
model_dir,
args.voice_dir,
).to(device)
# query speaker ids of a multi-speaker model.
if args.list_speaker_idxs:
print(
" > Available speaker ids: (Set --speaker_idx flag to one of these values to use the multi-speaker model."
)
print(synthesizer.tts_model.speaker_manager.name_to_id)
return
# query langauge ids of a multi-lingual model.
if args.list_language_idxs:
print(
" > Available language ids: (Set --language_idx flag to one of these values to use the multi-lingual model."
)
print(synthesizer.tts_model.language_manager.name_to_id)
return
# check the arguments against a multi-speaker model.
if synthesizer.tts_speakers_file and (not args.speaker_idx and not args.speaker_wav):
print(
" [!] Looks like you use a multi-speaker model. Define `--speaker_idx` to "
"select the target speaker. You can list the available speakers for this model by `--list_speaker_idxs`."
)
return
# RUN THE SYNTHESIS
if args.text:
print(" > Text: {}".format(args.text))
# kick it
if tts_path is not None:
wav = synthesizer.tts(
args.text,
speaker_name=args.speaker_idx,
language_name=args.language_idx,
speaker_wav=args.speaker_wav,
reference_wav=args.reference_wav,
style_wav=args.capacitron_style_wav,
style_text=args.capacitron_style_text,
reference_speaker_name=args.reference_speaker_idx,
)
elif vc_path is not None:
wav = synthesizer.voice_conversion(
source_wav=args.source_wav,
target_wav=args.target_wav,
)
elif model_dir is not None:
wav = synthesizer.tts(
args.text, speaker_name=args.speaker_idx, language_name=args.language_idx, speaker_wav=args.speaker_wav
)
# save the results
print(" > Saving output to {}".format(args.out_path))
synthesizer.save_wav(wav, args.out_path, pipe_out=pipe_out)
if __name__ == "__main__":
main()
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/pdt/pdtreplace.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Converts an RTN represented by FSTs and non-terminal labels into a PDT.
#include <cstring>
#include <string>
#include <vector>
#include <fst/flags.h>
#include <fst/extensions/pdt/getters.h>
#include <fst/extensions/pdt/pdtscript.h>
#include <fst/util.h>
#include <fst/vector-fst.h>
DEFINE_string(pdt_parentheses, "", "PDT parenthesis label pairs");
DEFINE_string(pdt_parser_type, "left",
"Construction method, one of: \"left\", \"left_sr\"");
DEFINE_int64(start_paren_labels, fst::kNoLabel,
"Index to use for the first inserted parentheses; if not "
"specified, the next available label beyond the highest output "
"label is used");
DEFINE_string(left_paren_prefix, "(_", "Prefix to attach to SymbolTable "
"labels for inserted left parentheses");
DEFINE_string(right_paren_prefix, ")_", "Prefix to attach to SymbolTable "
"labels for inserted right parentheses");
void Cleanup(std::vector<fst::script::LabelFstClassPair> *pairs) {
for (const auto &pair : *pairs) {
delete pair.second;
}
pairs->clear();
}
int main(int argc, char **argv) {
namespace s = fst::script;
using fst::script::FstClass;
using fst::script::VectorFstClass;
using fst::PdtParserType;
using fst::WriteLabelPairs;
string usage = "Converts an RTN represented by FSTs";
usage += " and non-terminal labels into PDT.\n\n Usage: ";
usage += argv[0];
usage += " root.fst rootlabel [rule1.fst label1 ...] [out.fst]\n";
std::set_new_handler(FailedNewHandler);
SET_FLAGS(usage.c_str(), &argc, &argv, true);
if (argc < 4) {
ShowUsage();
return 1;
}
const string in_name = argv[1];
const string out_name = argc % 2 == 0 ? argv[argc - 1] : "";
auto *ifst = FstClass::Read(in_name);
if (!ifst) return 1;
PdtParserType parser_type;
if (!s::GetPdtParserType(FLAGS_pdt_parser_type, &parser_type)) {
LOG(ERROR) << argv[0] << ": Unknown PDT parser type: "
<< FLAGS_pdt_parser_type;
delete ifst;
return 1;
}
std::vector<s::LabelFstClassPair> pairs;
// Note that if the root label is beyond the range of the underlying FST's
// labels, truncation will occur.
const auto root = atoll(argv[2]);
pairs.emplace_back(root, ifst);
for (auto i = 3; i < argc - 1; i += 2) {
ifst = FstClass::Read(argv[i]);
if (!ifst) {
Cleanup(&pairs);
return 1;
}
// Note that if the root label is beyond the range of the underlying FST's
// labels, truncation will occur.
const auto label = atoll(argv[i + 1]);
pairs.emplace_back(label, ifst);
}
VectorFstClass ofst(ifst->ArcType());
std::vector<s::LabelPair> parens;
s::PdtReplace(pairs, &ofst, &parens, root, parser_type,
FLAGS_start_paren_labels, FLAGS_left_paren_prefix,
FLAGS_right_paren_prefix);
Cleanup(&pairs);
if (!FLAGS_pdt_parentheses.empty()) {
if (!WriteLabelPairs(FLAGS_pdt_parentheses, parens)) return 1;
}
ofst.Write(out_name);
return 0;
}
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/taskcluster/test-training-extra_16k-linux-amd64-py36m-opt.yml | build:
template_file: test-linux-opt-base.tyml
dependencies:
- "linux-amd64-ctc-opt"
system_setup:
>
apt-get -qq update && apt-get -qq -y install ${training.packages_xenial.apt}
args:
tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-train-extra-tests.sh 3.6.10:m 16k"
workerType: "${docker.dsTests}"
metadata:
name: "DeepSpeech Linux AMD64 CPU 8kHz all training features Py3.6"
description: "Training (all features) a DeepSpeech LDC93S1 model for Linux/AMD64 8kHz Python 3.6, CPU only, optimized version"
| 0 |
coqui_public_repos/STT-models/mixtec/jemeyer | coqui_public_repos/STT-models/mixtec/jemeyer/v1.0.0/MODEL_CARD.md | # Model card for Yoloxóchitl Mixtec STT
Jump to section:
- [Model details](#model-details)
- [Intended use](#intended-use)
- [Performance Factors](#performance-factors)
- [Metrics](#metrics)
- [Training data](#training-data)
- [Evaluation data](#evaluation-data)
- [Ethical considerations](#ethical-considerations)
- [Caveats and recommendations](#caveats-and-recommendations)
## Model details
- Person or organization developing model: Originally trained by [Joe Meyer](https://www.linkedin.com/in/joe-meyer-25753951/).
- Model language: Yoloxóchitl Mixtec / / `xty`
- Model date: April 17, 2022
- Model type: `Speech-to-Text`
- Model version: `v0.1.0`
- Compatible with 🐸 STT version: `v1.0.0`
- License: CC BY-NC-SA 3.0
- Citation details: `@techreport{xty-stt, author = {Meyer,Joe}, title = {Yoloxóchitl Mixtec STT 0.1}, institution = {Coqui}, address = {\url{https://github.com/coqui-ai/STT-models}} year = {2022}, month = {April}, number = {STT-SLR89-XTY-0.1} }`
- Where to send questions or comments about the model: You can leave an issue on [`STT-model` issues](https://github.com/coqui-ai/STT-models/issues), open a new discussion on [`STT-model` discussions](https://github.com/coqui-ai/STT-models/discussions), or chat with us on [Gitter](https://gitter.im/coqui-ai/).
## Intended use
Speech-to-Text for the [Yoloxóchitl Mixtec Language](https://en.wikipedia.org/wiki/Yolox%C3%B3chitl_Mixtec) on 16kHz, mono-channel audio.
## Performance Factors
Factors relevant to Speech-to-Text performance include but are not limited to speaker demographics, recording quality, and background noise. Read more about STT performance factors [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data).
## Metrics
STT models are usually evaluated in terms of their transcription accuracy, deployment Real-Time Factor, and model size on disk.
#### Transcription Accuracy
The following Word Error Rates and Character Error Rates are reported for a modified data set from OpenSLR [SLR89](https://www.openslr.org/89/). The official `validated.tsv` had rows removed which had errors processing, and the data was re-processed by [Cmmon Voice Utils](https://github.com/ftyers/commonvoice-utils) to convert to 16kHz mono-channel PCM .wav files.
|Test Corpus|WER|CER|
|-----------|---|---|
|OpenSLR|48.85\%|18.04\%|
#### Real-Time Factor
Real-Time Factor (RTF) is defined as `processing-time / length-of-audio`. The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF.
Recorded average RTF on laptop CPU: ``
#### Model Size
`model.pbmm`: M
`model.tflite`: M
### Approaches to uncertainty and variability
Confidence scores and multiple paths from the decoding beam can be used to measure model uncertainty and provide multiple, variable transcripts for any processed audio.
## Training data
This model was trained on a modified data set from OpenSLR [SLR89](https://www.openslr.org/89/). The official `validated.tsv` had rows removed which had errors processing, and the data was re-processed by [Cmmon Voice Utils](https://github.com/ftyers/commonvoice-utils) to convert to 16kHz mono-channel PCM .wav files.
## Evaluation data
This model was evaluated on a modified data set from OpenSLR [SLR89](https://www.openslr.org/89/). The official `validated.tsv` had rows removed which had errors processing, and the data was re-processed by [Cmmon Voice Utils](https://github.com/ftyers/commonvoice-utils) to convert to 16kHz mono-channel PCM .wav files.
## Ethical considerations
Deploying a Speech-to-Text model into any production setting has ethical implications. You should consider these implications before use.
### Demographic Bias
You should assume every machine learning model has demographic bias unless proven otherwise. For STT models, it is often the case that transcription accuracy is better for men than it is for women. If you are using this model in production, you should acknowledge this as a potential issue.
### Surveillance
Speech-to-Text may be mis-used to invade the privacy of others by recording and mining information from private conversations. This kind of individual privacy is protected by law in may countries. You should not assume consent to record and analyze private speech.
## Caveats and recommendations
Machine learning models (like this STT model) perform best on data that is similar to the data on which they were trained. Read about what to expect from an STT model with regard to your data [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data).
In most applications, it is recommended that you [train your own language model](https://stt.readthedocs.io/en/latest/LANGUAGE_MODEL.html) to improve transcription accuracy on your speech data.
| 0 |
coqui_public_repos/TTS/TTS/tts/utils/text | coqui_public_repos/TTS/TTS/tts/utils/text/korean/ko_dictionary.py | # coding: utf-8
# Add the word you want to the dictionary.
etc_dictionary = {"1+1": "원플러스원", "2+1": "투플러스원"}
english_dictionary = {
"KOREA": "코리아",
"IDOL": "아이돌",
"IT": "아이티",
"IQ": "아이큐",
"UP": "업",
"DOWN": "다운",
"PC": "피씨",
"CCTV": "씨씨티비",
"SNS": "에스엔에스",
"AI": "에이아이",
"CEO": "씨이오",
"A": "에이",
"B": "비",
"C": "씨",
"D": "디",
"E": "이",
"F": "에프",
"G": "지",
"H": "에이치",
"I": "아이",
"J": "제이",
"K": "케이",
"L": "엘",
"M": "엠",
"N": "엔",
"O": "오",
"P": "피",
"Q": "큐",
"R": "알",
"S": "에스",
"T": "티",
"U": "유",
"V": "브이",
"W": "더블유",
"X": "엑스",
"Y": "와이",
"Z": "제트",
}
| 0 |
coqui_public_repos/TTS/tests | coqui_public_repos/TTS/tests/tts_tests/test_tacotron_train.py | import glob
import os
import shutil
from trainer import get_last_checkpoint
from tests import get_device_id, get_tests_output_path, run_cli
from TTS.tts.configs.tacotron_config import TacotronConfig
config_path = os.path.join(get_tests_output_path(), "test_model_config.json")
output_path = os.path.join(get_tests_output_path(), "train_outputs")
config = TacotronConfig(
batch_size=8,
eval_batch_size=8,
num_loader_workers=0,
num_eval_loader_workers=0,
text_cleaner="english_cleaners",
use_phonemes=False,
phoneme_language="en-us",
phoneme_cache_path=os.path.join(get_tests_output_path(), "train_outputs/phoneme_cache/"),
run_eval=True,
test_delay_epochs=-1,
epochs=1,
print_step=1,
test_sentences=[
"Be a voice, not an echo.",
],
print_eval=True,
r=5,
max_decoder_steps=50,
)
config.audio.do_trim_silence = True
config.audio.trim_db = 60
config.save_json(config_path)
# train the model for one epoch
command_train = (
f"CUDA_VISIBLE_DEVICES='{get_device_id()}' python TTS/bin/train_tts.py --config_path {config_path} "
f"--coqpit.output_path {output_path} "
"--coqpit.datasets.0.formatter ljspeech "
"--coqpit.datasets.0.meta_file_train metadata.csv "
"--coqpit.datasets.0.meta_file_val metadata.csv "
"--coqpit.datasets.0.path tests/data/ljspeech "
"--coqpit.test_delay_epochs 0"
)
run_cli(command_train)
# Find latest folder
continue_path = max(glob.glob(os.path.join(output_path, "*/")), key=os.path.getmtime)
# Inference using TTS API
continue_config_path = os.path.join(continue_path, "config.json")
continue_restore_path, _ = get_last_checkpoint(continue_path)
out_wav_path = os.path.join(get_tests_output_path(), "output.wav")
inference_command = f"CUDA_VISIBLE_DEVICES='{get_device_id()}' tts --text 'This is an example.' --config_path {continue_config_path} --model_path {continue_restore_path} --out_path {out_wav_path}"
run_cli(inference_command)
# restore the model and continue training for one more epoch
command_train = f"CUDA_VISIBLE_DEVICES='{get_device_id()}' python TTS/bin/train_tts.py --continue_path {continue_path} "
run_cli(command_train)
shutil.rmtree(continue_path)
| 0 |
coqui_public_repos/STT/native_client/dotnet/STTClient | coqui_public_repos/STT/native_client/dotnet/STTClient/Extensions/NativeExtensions.cs | using STTClient.Structs;
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace STTClient.Extensions
{
internal static class NativeExtensions
{
/// <summary>
/// Converts native pointer to UTF-8 encoded string.
/// </summary>
/// <param name="intPtr">Native pointer.</param>
/// <param name="releasePtr">Optional parameter to release the native pointer.</param>
/// <returns>Result string.</returns>
internal static string PtrToString(this IntPtr intPtr, bool releasePtr = true)
{
int len = 0;
while (Marshal.ReadByte(intPtr, len) != 0) ++len;
byte[] buffer = new byte[len];
Marshal.Copy(intPtr, buffer, 0, buffer.Length);
if (releasePtr)
NativeImp.STT_FreeString(intPtr);
string result = Encoding.UTF8.GetString(buffer);
return result;
}
/// <summary>
/// Converts a pointer into managed TokenMetadata object.
/// </summary>
/// <param name="intPtr">Native pointer.</param>
/// <returns>TokenMetadata managed object.</returns>
private static Models.TokenMetadata PtrToTokenMetadata(this IntPtr intPtr)
{
var token = Marshal.PtrToStructure<TokenMetadata>(intPtr);
var managedToken = new Models.TokenMetadata
{
Timestep = token.timestep,
StartTime = token.start_time,
Text = token.text.PtrToString(releasePtr: false)
};
return managedToken;
}
/// <summary>
/// Converts a pointer into managed CandidateTranscript object.
/// </summary>
/// <param name="intPtr">Native pointer.</param>
/// <returns>CandidateTranscript managed object.</returns>
private static Models.CandidateTranscript PtrToCandidateTranscript(this IntPtr intPtr)
{
var managedTranscript = new Models.CandidateTranscript();
var transcript = Marshal.PtrToStructure<CandidateTranscript>(intPtr);
managedTranscript.Tokens = new Models.TokenMetadata[transcript.num_tokens];
managedTranscript.Confidence = transcript.confidence;
//we need to manually read each item from the native ptr using its size
var sizeOfTokenMetadata = Marshal.SizeOf<TokenMetadata>();
for (int i = 0; i < transcript.num_tokens; i++)
{
managedTranscript.Tokens[i] = transcript.tokens.PtrToTokenMetadata();
transcript.tokens += sizeOfTokenMetadata;
}
return managedTranscript;
}
/// <summary>
/// Converts a pointer into managed Metadata object.
/// </summary>
/// <param name="intPtr">Native pointer.</param>
/// <returns>Metadata managed object.</returns>
internal static Models.Metadata PtrToMetadata(this IntPtr intPtr)
{
var managedMetadata = new Models.Metadata();
var metadata = Marshal.PtrToStructure<Metadata>(intPtr);
managedMetadata.Transcripts = new Models.CandidateTranscript[metadata.num_transcripts];
//we need to manually read each item from the native ptr using its size
var sizeOfCandidateTranscript = Marshal.SizeOf<CandidateTranscript>();
for (int i = 0; i < metadata.num_transcripts; i++)
{
managedMetadata.Transcripts[i] = metadata.transcripts.PtrToCandidateTranscript();
metadata.transcripts += sizeOfCandidateTranscript;
}
NativeImp.STT_FreeMetadata(intPtr);
return managedMetadata;
}
}
}
| 0 |
coqui_public_repos/TTS/TTS/vc/modules/freevc | coqui_public_repos/TTS/TTS/vc/modules/freevc/wavlm/__init__.py | import os
import urllib.request
import torch
from TTS.utils.generic_utils import get_user_data_dir
from TTS.vc.modules.freevc.wavlm.wavlm import WavLM, WavLMConfig
model_uri = "https://github.com/coqui-ai/TTS/releases/download/v0.13.0_models/WavLM-Large.pt"
def get_wavlm(device="cpu"):
"""Download the model and return the model object."""
output_path = get_user_data_dir("tts")
output_path = os.path.join(output_path, "wavlm")
if not os.path.exists(output_path):
os.makedirs(output_path)
output_path = os.path.join(output_path, "WavLM-Large.pt")
if not os.path.exists(output_path):
print(f" > Downloading WavLM model to {output_path} ...")
urllib.request.urlretrieve(model_uri, output_path)
checkpoint = torch.load(output_path, map_location=torch.device(device))
cfg = WavLMConfig(checkpoint["cfg"])
wavlm = WavLM(cfg).to(device)
wavlm.load_state_dict(checkpoint["model"])
wavlm.eval()
return wavlm
if __name__ == "__main__":
wavlm = get_wavlm()
| 0 |
coqui_public_repos/STT-models/swahili/coqui | coqui_public_repos/STT-models/swahili/coqui/v8.0-large-vocab/LICENSE |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
| 0 |
coqui_public_repos/STT-models/odia/itml | coqui_public_repos/STT-models/odia/itml/v0.1.0/MODEL_CARD.md | # Model card for Odia STT
Jump to section:
- [Model details](#model-details)
- [Intended use](#intended-use)
- [Performance Factors](#performance-factors)
- [Metrics](#metrics)
- [Training data](#training-data)
- [Evaluation data](#evaluation-data)
- [Ethical considerations](#ethical-considerations)
- [Caveats and recommendations](#caveats-and-recommendations)
## Model details
- Person or organization developing model: Originally trained by [Francis Tyers](https://scholar.google.fr/citations?user=o5HSM6cAAAAJ) and the [Inclusive Technology for Marginalised Languages](https://itml.cl.indiana.edu/) group.
- Model language: Odia / ଓଡ଼ିଆ / `or`
- Model date: April 9, 2021
- Model type: `Speech-to-Text`
- Model version: `v0.1.0`
- Compatible with 🐸 STT version: `v0.9.3`
- License: AGPL
- Citation details: `@techreport{odia-stt, author = {Tyers,Francis}, title = {Odia STT 0.1}, institution = {Coqui}, address = {\url{https://github.com/coqui-ai/STT-models}} year = {2021}, month = {April}, number = {STT-CV6.1-OR-0.1} }`
- Where to send questions or comments about the model: You can leave an issue on [`STT-model` issues](https://github.com/coqui-ai/STT-models/issues), open a new discussion on [`STT-model` discussions](https://github.com/coqui-ai/STT-models/discussions), or chat with us on [Gitter](https://gitter.im/coqui-ai/).
## Intended use
Speech-to-Text for the [Odia Language](https://en.wikipedia.org/wiki/Odia_language) on 16kHz, mono-channel audio.
## Performance Factors
Factors relevant to Speech-to-Text performance include but are not limited to speaker demographics, recording quality, and background noise. Read more about STT performance factors [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data).
## Metrics
STT models are usually evaluated in terms of their transcription accuracy, deployment Real-Time Factor, and model size on disk.
#### Transcription Accuracy
The following Word Error Rates and Character Error Rates are reported on [omnilingo](https://tepozcatl.omnilingo.cc/or/).
|Test Corpus|WER|CER|
|-----------|---|---|
|Common Voice|98.9\%|55.2\%|
#### Real-Time Factor
Real-Time Factor (RTF) is defined as `processing-time / length-of-audio`. The exact real-time factor of an STT model will depend on the hardware setup, so you may experience a different RTF.
Recorded average RTF on laptop CPU: ``
#### Model Size
`model.pbmm`: 181M
`model.tflite`: 46M
### Approaches to uncertainty and variability
Confidence scores and multiple paths from the decoding beam can be used to measure model uncertainty and provide multiple, variable transcripts for any processed audio.
## Training data
This model was trained on Common Voice 6.1 train.
## Evaluation data
The Model was evaluated on Common Voice 6.1 test.
## Ethical considerations
Deploying a Speech-to-Text model into any production setting has ethical implications. You should consider these implications before use.
### Demographic Bias
You should assume every machine learning model has demographic bias unless proven otherwise. For STT models, it is often the case that transcription accuracy is better for men than it is for women. If you are using this model in production, you should acknowledge this as a potential issue.
### Surveillance
Speech-to-Text may be mis-used to invade the privacy of others by recording and mining information from private conversations. This kind of individual privacy is protected by law in may countries. You should not assume consent to record and analyze private speech.
## Caveats and recommendations
Machine learning models (like this STT model) perform best on data that is similar to the data on which they were trained. Read about what to expect from an STT model with regard to your data [here](https://stt.readthedocs.io/en/latest/DEPLOYMENT.html#how-will-a-model-perform-on-my-data).
In most applications, it is recommended that you [train your own language model](https://stt.readthedocs.io/en/latest/LANGUAGE_MODEL.html) to improve transcription accuracy on your speech data.
| 0 |
coqui_public_repos/inference-engine/third_party/kenlm/util | coqui_public_repos/inference-engine/third_party/kenlm/util/double-conversion/utils.h | // Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef DOUBLE_CONVERSION_UTILS_H_
#define DOUBLE_CONVERSION_UTILS_H_
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifndef ASSERT
#define ASSERT(condition) \
assert(condition);
#endif
#ifndef UNIMPLEMENTED
#define UNIMPLEMENTED() (abort())
#endif
#ifndef DOUBLE_CONVERSION_NO_RETURN
#ifdef _MSC_VER
#define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn)
#else
#define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn))
#endif
#endif
#ifndef UNREACHABLE
#ifdef _MSC_VER
void DOUBLE_CONVERSION_NO_RETURN abort_noreturn();
inline void abort_noreturn() { abort(); }
#define UNREACHABLE() (abort_noreturn())
#else
#define UNREACHABLE() (abort())
#endif
#endif
// Double operations detection based on target architecture.
// Linux uses a 80bit wide floating point stack on x86. This induces double
// rounding, which in turn leads to wrong results.
// An easy way to test if the floating-point operations are correct is to
// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then
// the result is equal to 89255e-22.
// The best way to test this, is to create a division-function and to compare
// the output of the division with the expected result. (Inlining must be
// disabled.)
// On Linux,x86 89255e-22 != Div_double(89255.0/1e22)
#if defined(_M_X64) || defined(__x86_64__) || \
defined(__ARMEL__) || defined(__avr32__) || \
defined(__hppa__) || defined(__ia64__) || \
defined(__mips__) || \
defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
defined(__SH4__) || defined(__alpha__) || \
defined(_MIPS_ARCH_MIPS32R2) || \
defined(__AARCH64EL__) || defined(__aarch64__) || \
defined(__riscv)
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
#elif defined(__mc68000__)
#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
#if defined(_WIN32)
// Windows uses a 64bit wide floating point stack.
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
#else
#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
#endif // _WIN32
#else
#error Target architecture was not detected as supported by Double-Conversion.
#endif
#if defined(__GNUC__)
#define DOUBLE_CONVERSION_UNUSED __attribute__((unused))
#else
#define DOUBLE_CONVERSION_UNUSED
#endif
#if defined(_WIN32) && !defined(__MINGW32__)
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t; // NOLINT
typedef unsigned short uint16_t; // NOLINT
typedef int int32_t;
typedef unsigned int uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
// intptr_t and friends are defined in crtdefs.h through stdio.h.
#else
#include <stdint.h>
#endif
typedef uint16_t uc16;
// The following macro works on both 32 and 64-bit platforms.
// Usage: instead of writing 0x1234567890123456
// write UINT64_2PART_C(0x12345678,90123456);
#define UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
// The expression ARRAY_SIZE(a) is a compile-time constant of type
// size_t which represents the number of elements of the given
// array. You should only use ARRAY_SIZE on statically allocated
// arrays.
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(a) \
((sizeof(a) / sizeof(*(a))) / \
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
#endif
// A macro to disallow the evil copy constructor and operator= functions
// This should be used in the private: declarations for a class
#ifndef DISALLOW_COPY_AND_ASSIGN
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
#endif
// A macro to disallow all the implicit constructors, namely the
// default constructor, copy constructor and operator= functions.
//
// This should be used in the private: declarations for a class
// that wants to prevent anyone from instantiating it. This is
// especially useful for classes containing only static methods.
#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
TypeName(); \
DISALLOW_COPY_AND_ASSIGN(TypeName)
#endif
namespace kenlm_double_conversion {
static const int kCharSize = sizeof(char);
// Returns the maximum of the two parameters.
template <typename T>
static T Max(T a, T b) {
return a < b ? b : a;
}
// Returns the minimum of the two parameters.
template <typename T>
static T Min(T a, T b) {
return a < b ? a : b;
}
inline int StrLength(const char* string) {
size_t length = strlen(string);
ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
return static_cast<int>(length);
}
// This is a simplified version of V8's Vector class.
template <typename T>
class Vector {
public:
Vector() : start_(NULL), length_(0) {}
Vector(T* data, int len) : start_(data), length_(len) {
ASSERT(len == 0 || (len > 0 && data != NULL));
}
// Returns a vector using the same backing storage as this one,
// spanning from and including 'from', to but not including 'to'.
Vector<T> SubVector(int from, int to) {
ASSERT(to <= length_);
ASSERT(from < to);
ASSERT(0 <= from);
return Vector<T>(start() + from, to - from);
}
// Returns the length of the vector.
int length() const { return length_; }
// Returns whether or not the vector is empty.
bool is_empty() const { return length_ == 0; }
// Returns the pointer to the start of the data in the vector.
T* start() const { return start_; }
// Access individual vector elements - checks bounds in debug mode.
T& operator[](int index) const {
ASSERT(0 <= index && index < length_);
return start_[index];
}
T& first() { return start_[0]; }
T& last() { return start_[length_ - 1]; }
private:
T* start_;
int length_;
};
// Helper class for building result strings in a character buffer. The
// purpose of the class is to use safe operations that checks the
// buffer bounds on all operations in debug mode.
class StringBuilder {
public:
StringBuilder(char* buffer, int buffer_size)
: buffer_(buffer, buffer_size), position_(0) { }
~StringBuilder() { if (!is_finalized()) Finalize(); }
int size() const { return buffer_.length(); }
// Get the current position in the builder.
int position() const {
ASSERT(!is_finalized());
return position_;
}
// Reset the position.
void Reset() { position_ = 0; }
// Add a single character to the builder. It is not allowed to add
// 0-characters; use the Finalize() method to terminate the string
// instead.
void AddCharacter(char c) {
ASSERT(c != '\0');
ASSERT(!is_finalized() && position_ < buffer_.length());
buffer_[position_++] = c;
}
// Add an entire string to the builder. Uses strlen() internally to
// compute the length of the input string.
void AddString(const char* s) {
AddSubstring(s, StrLength(s));
}
// Add the first 'n' characters of the given string 's' to the
// builder. The input string must have enough characters.
void AddSubstring(const char* s, int n) {
ASSERT(!is_finalized() && position_ + n < buffer_.length());
ASSERT(static_cast<size_t>(n) <= strlen(s));
memmove(&buffer_[position_], s, n * kCharSize);
position_ += n;
}
// Add character padding to the builder. If count is non-positive,
// nothing is added to the builder.
void AddPadding(char c, int count) {
for (int i = 0; i < count; i++) {
AddCharacter(c);
}
}
// Finalize the string by 0-terminating it and returning the buffer.
char* Finalize() {
ASSERT(!is_finalized() && position_ < buffer_.length());
buffer_[position_] = '\0';
// Make sure nobody managed to add a 0-character to the
// buffer while building the string.
ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
position_ = -1;
ASSERT(is_finalized());
return buffer_.start();
}
private:
Vector<char> buffer_;
int position_;
bool is_finalized() const { return position_ < 0; }
DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
};
// The type-based aliasing rule allows the compiler to assume that pointers of
// different types (for some definition of different) never alias each other.
// Thus the following code does not work:
//
// float f = foo();
// int fbits = *(int*)(&f);
//
// The compiler 'knows' that the int pointer can't refer to f since the types
// don't match, so the compiler may cache f in a register, leaving random data
// in fbits. Using C++ style casts makes no difference, however a pointer to
// char data is assumed to alias any other pointer. This is the 'memcpy
// exception'.
//
// Bit_cast uses the memcpy exception to move the bits from a variable of one
// type of a variable of another type. Of course the end result is likely to
// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
// will completely optimize BitCast away.
//
// There is an additional use for BitCast.
// Recent gccs will warn when they see casts that may result in breakage due to
// the type-based aliasing rule. If you have checked that there is no breakage
// you can use BitCast to cast one pointer type to another. This confuses gcc
// enough that it can no longer see that you have cast one pointer type to
// another thus avoiding the warning.
template <class Dest, class Source>
inline Dest BitCast(const Source& source) {
// Compile time assertion: sizeof(Dest) == sizeof(Source)
// A compile error here means your Dest and Source have different sizes.
DOUBLE_CONVERSION_UNUSED
typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
Dest dest;
memmove(&dest, &source, sizeof(dest));
return dest;
}
template <class Dest, class Source>
inline Dest BitCast(Source* source) {
return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
}
} // namespace kenlm_double_conversion
#endif // DOUBLE_CONVERSION_UTILS_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/bin/fstinvert-main.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Inverts a transduction.
#include <cstring>
#include <memory>
#include <string>
#include <fst/flags.h>
#include <fst/script/invert.h>
int fstinvert_main(int argc, char **argv) {
namespace s = fst::script;
using fst::script::MutableFstClass;
string usage = "Inverts a transduction.\n\n Usage: ";
usage += argv[0];
usage += " [in.fst [out.fst]]\n";
std::set_new_handler(FailedNewHandler);
SET_FLAGS(usage.c_str(), &argc, &argv, true);
if (argc > 3) {
ShowUsage();
return 1;
}
const string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : "";
const string out_name = argc > 2 ? argv[2] : "";
std::unique_ptr<MutableFstClass> fst(MutableFstClass::Read(in_name, true));
if (!fst) return 1;
s::Invert(fst.get());
return !fst->Write(out_name);
}
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/openfst.user.props | <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!--
User settings, to simplify setup. The names and values of make variables
used by MsBuild scripts are not obvious, so I thought it would be easier
if the list of user choices in available in a single file.
All settings are disabled by default. Enable any of them by removing the
'Condition="false"' part.
You can instead specify these values in MSBuild command line. For example,
you can put the following command into a build.cmd file:
msbuild openfst.sln -v:m -m -t:Build ^
-p:Platform=x64 ^
-p:Configuration=Release ^
-p:PlatformToolset=v141 ^
-p:WindowsTargetPlatformVersion=10.0.17134.0 ^
-p:EnableEnhancedInstructionSet=AdvancedVectorExtensions
-->
<!-- Toolset (default v141). Other compilers (Intel C++) may be specified. -->
<PropertyGroup>
<!-- v140 = 14.0, comes with VS14 aka VS 2015 -->
<PlatformToolset Condition="false" >v140</PlatformToolset>
<!-- v141 = 14.1, comes with VS15 aka VS 2017. This is the default. -->
<PlatformToolset Condition="true" >v141</PlatformToolset>
</PropertyGroup>
<!-- SDK version (default: toolset's default, likely 8.1). Note that v141 has
8.1 as the default SDK, but that SDK may not be installed with VS 2017
default C++ workload. If you get a message "MSB8036: The Windows SDK
version 8.1 was not found", check if you have any of Window 10 SDK
versions. Then change 'false' to 'true' for the version you have installed.
Run "x{86,64} Native Tools Command Prompt for VS 201{5,7}" from the
Start Menu, and type "set WindowsSDKVersion". The value of the
environment variable shows the installed version of the Windows 10 SDK.
You can also look for the versions in subdirectories of the folder
%ProgramFiles(x86)%\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP
(assuming the default install location for Windows SDK). Every subdirectory
name is the Windows SDK version that you can use.
I am including a (possibly incomplete) list of released Windows 10 SDK
versions (any one would work, as long as you have it installed). -->
<PropertyGroup>
<!-- Windows 10 Update 1803 (April 2018) -->
<WindowsTargetPlatformVersion Condition="true" >10.0.17134.0</WindowsTargetPlatformVersion>
<!-- Windows 10 Fall Creators Update -->
<WindowsTargetPlatformVersion Condition="false" >10.0.16299.0</WindowsTargetPlatformVersion>
<!-- Windows 10 Creators Update -->
<WindowsTargetPlatformVersion Condition="false" >10.0.15063.0</WindowsTargetPlatformVersion>
<!-- Windows 10 Anniversary Edition -->
<WindowsTargetPlatformVersion Condition="false" >10.0.14393.0</WindowsTargetPlatformVersion>
<!-- Windows 10 November 2015 SDK update-->
<WindowsTargetPlatformVersion Condition="false" >10.0.10586.0</WindowsTargetPlatformVersion>
<!-- Windows 10 original SDK, can have either of the two versions below: -->
<WindowsTargetPlatformVersion Condition="false" >10.0.10240.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformVersion Condition="false" >10.0.26624.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<!-- Enhanced instruction set (default SSE2, I believe).
NOTE: In kkm's experience, AVX helps the performance a little
(few % at most), AVX2 does not improve performance further. YMMV:
Maybe it's our FST structure that does not yield to optimization.
Currently, there is no MS c2 codegen for AVX512 instructions.
Note: cl 32-bit compiler likely does not support AVX/AVX2. -->
<PropertyGroup>
<!-- AVX -->
<EnableEnhancedInstructionSet Condition="true" >AdvancedVectorExtensions</EnableEnhancedInstructionSet>
<!-- AVX2 -->
<EnableEnhancedInstructionSet Condition="true" >AdvancedVectorExtensions2</EnableEnhancedInstructionSet>
</PropertyGroup>
</Project>
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/bin/fstintersect-main.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Intersects two FSTs.
#include <cstring>
#include <memory>
#include <string>
#include <fst/flags.h>
#include <fst/log.h>
#include <fst/script/getters.h>
#include <fst/script/intersect.h>
DECLARE_string(compose_filter);
DECLARE_bool(connect);
int fstintersect_main(int argc, char **argv) {
namespace s = fst::script;
using fst::ComposeFilter;
using fst::script::FstClass;
using fst::script::VectorFstClass;
string usage = "Intersects two FSAs.\n\n Usage: ";
usage += argv[0];
usage += " in1.fst in2.fst [out.fst]\n";
usage += " Flags: connect\n";
std::set_new_handler(FailedNewHandler);
SET_FLAGS(usage.c_str(), &argc, &argv, true);
if (argc < 3 || argc > 4) {
ShowUsage();
return 1;
}
const string in1_name = strcmp(argv[1], "-") == 0 ? "" : argv[1];
const string in2_name = strcmp(argv[2], "-") == 0 ? "" : argv[2];
const string out_name = argc > 3 ? argv[3] : "";
if (in1_name.empty() && in2_name.empty()) {
LOG(ERROR) << argv[0] << ": Can't take both inputs from standard input";
return 1;
}
std::unique_ptr<FstClass> ifst1(FstClass::Read(in1_name));
if (!ifst1) return 1;
std::unique_ptr<FstClass> ifst2(FstClass::Read(in2_name));
if (!ifst2) return 1;
VectorFstClass ofst(ifst1->ArcType());
ComposeFilter compose_filter;
if (!s::GetComposeFilter(FLAGS_compose_filter, &compose_filter)) {
LOG(ERROR) << argv[0] << ": Unknown or unsupported compose filter type: "
<< FLAGS_compose_filter;
return 1;
}
const fst::IntersectOptions opts(FLAGS_connect, compose_filter);
s::Intersect(*ifst1, *ifst2, &ofst, opts);
return !ofst.Write(out_name);
}
| 0 |
coqui_public_repos/inference-engine/third_party/kenlm/lm | coqui_public_repos/inference-engine/third_party/kenlm/lm/wrappers/nplm.hh | #ifndef LM_WRAPPERS_NPLM_H
#define LM_WRAPPERS_NPLM_H
#include "lm/facade.hh"
#include "lm/max_order.hh"
#include "util/string_piece.hh"
#include <boost/thread/tss.hpp>
#include <boost/scoped_ptr.hpp>
/* Wrapper to NPLM "by Ashish Vaswani, with contributions from David Chiang
* and Victoria Fossum."
* http://nlg.isi.edu/software/nplm/
*/
namespace nplm {
class vocabulary;
class neuralLM;
} // namespace nplm
namespace lm {
namespace np {
class Vocabulary : public base::Vocabulary {
public:
Vocabulary(const nplm::vocabulary &vocab);
~Vocabulary();
WordIndex Index(const std::string &str) const;
// TODO: lobby them to support StringPiece
WordIndex Index(const StringPiece &str) const {
return Index(std::string(str.data(), str.size()));
}
lm::WordIndex NullWord() const { return null_word_; }
private:
const nplm::vocabulary &vocab_;
const lm::WordIndex null_word_;
};
// Sorry for imposing my limitations on your code.
#define NPLM_MAX_ORDER 7
struct State {
WordIndex words[NPLM_MAX_ORDER - 1];
};
class Backend;
class Model : public lm::base::ModelFacade<Model, State, Vocabulary> {
private:
typedef lm::base::ModelFacade<Model, State, Vocabulary> P;
public:
// Does this look like an NPLM?
static bool Recognize(const std::string &file);
explicit Model(const std::string &file, std::size_t cache_size = 1 << 20);
~Model();
FullScoreReturn FullScore(const State &from, const WordIndex new_word, State &out_state) const;
FullScoreReturn FullScoreForgotState(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, State &out_state) const;
private:
boost::scoped_ptr<nplm::neuralLM> base_instance_;
mutable boost::thread_specific_ptr<Backend> backend_;
Vocabulary vocab_;
lm::WordIndex null_word_;
const std::size_t cache_size_;
};
} // namespace np
} // namespace lm
#endif // LM_WRAPPERS_NPLM_H
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/bin/fstpush-main.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Pushes weights and/or output labels in an FST toward the initial or final
// states.
#include <cstring>
#include <memory>
#include <string>
#include <fst/flags.h>
#include <fst/script/getters.h>
#include <fst/script/push.h>
DECLARE_double(delta);
DECLARE_bool(push_weights);
DECLARE_bool(push_labels);
DECLARE_bool(remove_total_weight);
DECLARE_bool(remove_common_affix);
DECLARE_bool(to_final);
int fstpush_main(int argc, char **argv) {
namespace s = fst::script;
using fst::script::FstClass;
using fst::script::VectorFstClass;
string usage = "Pushes weights and/or olabels in an FST.\n\n Usage: ";
usage += argv[0];
usage += " [in.fst [out.fst]]\n";
std::set_new_handler(FailedNewHandler);
SET_FLAGS(usage.c_str(), &argc, &argv, true);
if (argc > 3) {
ShowUsage();
return 1;
}
string in_name = (argc > 1 && strcmp(argv[1], "-") != 0) ? argv[1] : "";
string out_name = argc > 2 ? argv[2] : "";
std::unique_ptr<FstClass> ifst(FstClass::Read(in_name));
if (!ifst) return 1;
const auto flags =
s::GetPushFlags(FLAGS_push_weights, FLAGS_push_labels,
FLAGS_remove_total_weight, FLAGS_remove_common_affix);
VectorFstClass ofst(ifst->ArcType());
s::Push(*ifst, &ofst, flags, s::GetReweightType(FLAGS_to_final),
FLAGS_delta);
return !ofst.Write(out_name);
}
| 0 |
coqui_public_repos/open-bible-scripts | coqui_public_repos/open-bible-scripts/data/LANGS.txt | akuapem-twi
arabic
asante-twi
chichewa
ewe
hausa
kikuyu
kurdi-sorani
lingala
luganda
luo
polish
vietnamese
yoruba
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/test/weight_test.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Regression test for FST weights.
#include <cstdlib>
#include <ctime>
#include <fst/flags.h>
#include <fst/log.h>
#include <fst/expectation-weight.h>
#include <fst/float-weight.h>
#include <fst/lexicographic-weight.h>
#include <fst/power-weight.h>
#include <fst/product-weight.h>
#include <fst/set-weight.h>
#include <fst/signed-log-weight.h>
#include <fst/sparse-power-weight.h>
#include <fst/string-weight.h>
#include <fst/union-weight.h>
#include "./weight-tester.h"
DEFINE_int32(seed, -1, "random seed");
DEFINE_int32(repeat, 10000, "number of test repetitions");
namespace {
using fst::Adder;
using fst::ExpectationWeight;
using fst::GALLIC;
using fst::GallicWeight;
using fst::LexicographicWeight;
using fst::LogWeight;
using fst::LogWeightTpl;
using fst::MinMaxWeight;
using fst::MinMaxWeightTpl;
using fst::NaturalLess;
using fst::PowerWeight;
using fst::ProductWeight;
using fst::SetWeight;
using fst::SET_INTERSECT_UNION;
using fst::SET_UNION_INTERSECT;
using fst::SET_BOOLEAN;
using fst::SignedLogWeight;
using fst::SignedLogWeightTpl;
using fst::SparsePowerWeight;
using fst::StringWeight;
using fst::STRING_LEFT;
using fst::STRING_RIGHT;
using fst::TropicalWeight;
using fst::TropicalWeightTpl;
using fst::UnionWeight;
using fst::WeightConvert;
using fst::WeightGenerate;
using fst::WeightTester;
template <class T>
void TestTemplatedWeights(int repeat) {
using TropicalWeightGenerate = WeightGenerate<TropicalWeightTpl<T>>;
TropicalWeightGenerate tropical_generate;
WeightTester<TropicalWeightTpl<T>, TropicalWeightGenerate> tropical_tester(
tropical_generate);
tropical_tester.Test(repeat);
using LogWeightGenerate = WeightGenerate<LogWeightTpl<T>>;
LogWeightGenerate log_generate;
WeightTester<LogWeightTpl<T>, LogWeightGenerate> log_tester(log_generate);
log_tester.Test(repeat);
using MinMaxWeightGenerate = WeightGenerate<MinMaxWeightTpl<T>>;
MinMaxWeightGenerate minmax_generate(true);
WeightTester<MinMaxWeightTpl<T>, MinMaxWeightGenerate> minmax_tester(
minmax_generate);
minmax_tester.Test(repeat);
using SignedLogWeightGenerate = WeightGenerate<SignedLogWeightTpl<T>>;
SignedLogWeightGenerate signedlog_generate;
WeightTester<SignedLogWeightTpl<T>, SignedLogWeightGenerate>
signedlog_tester(signedlog_generate);
signedlog_tester.Test(repeat);
}
template <class Weight>
void TestAdder(int n) {
Weight sum = Weight::Zero();
Adder<Weight> adder;
for (int i = 0; i < n; ++i) {
sum = Plus(sum, Weight::One());
adder.Add(Weight::One());
}
CHECK(ApproxEqual(sum, adder.Sum()));
}
template <class Weight>
void TestSignedAdder(int n) {
Weight sum = Weight::Zero();
Adder<Weight> adder;
const Weight minus_one = Minus(Weight::Zero(), Weight::One());
for (int i = 0; i < n; ++i) {
if (i < n/4 || i > 3*n/4) {
sum = Plus(sum, Weight::One());
adder.Add(Weight::One());
} else {
sum = Minus(sum, Weight::One());
adder.Add(minus_one);
}
}
CHECK(ApproxEqual(sum, adder.Sum()));
}
template <typename Weight1, typename Weight2>
void TestWeightConversion(Weight1 w1) {
// Tests round-trp conversion.
WeightConvert<Weight2, Weight1> to_w1_;
WeightConvert<Weight1, Weight2> to_w2_;
Weight2 w2 = to_w2_(w1);
Weight1 nw1 = to_w1_(w2);
CHECK_EQ(w1, nw1);
}
template <typename FromWeight, typename ToWeight>
void TestWeightCopy(FromWeight w) {
// Test copy constructor.
const ToWeight to_copied(w);
const FromWeight roundtrip_copied(to_copied);
CHECK_EQ(w, roundtrip_copied);
// Test copy assign.
ToWeight to_copy_assigned;
to_copy_assigned = w;
CHECK_EQ(to_copied, to_copy_assigned);
FromWeight roundtrip_copy_assigned;
roundtrip_copy_assigned = to_copy_assigned;
CHECK_EQ(w, roundtrip_copy_assigned);
}
template <typename FromWeight, typename ToWeight>
void TestWeightMove(FromWeight w) {
// Assume FromWeight -> FromWeight copy works.
const FromWeight orig(w);
ToWeight to_moved(std::move(w));
const FromWeight roundtrip_moved(std::move(to_moved));
CHECK_EQ(orig, roundtrip_moved);
// Test move assign.
w = orig;
ToWeight to_move_assigned;
to_move_assigned = std::move(w);
FromWeight roundtrip_move_assigned;
roundtrip_move_assigned = std::move(to_move_assigned);
CHECK_EQ(orig, roundtrip_move_assigned);
}
template <class Weight>
void TestImplicitConversion() {
// Only test a few of the operations; assumes they are implemented with the
// same pattern.
CHECK(Weight(2.0f) == 2.0f);
CHECK(Weight(2.0) == 2.0);
CHECK(2.0f == Weight(2.0f));
CHECK(2.0 == Weight(2.0));
CHECK_EQ(Weight::Zero(), Times(Weight::Zero(), 3.0f));
CHECK_EQ(Weight::Zero(), Times(Weight::Zero(), 3.0));
CHECK_EQ(Weight::Zero(), Times(3.0, Weight::Zero()));
CHECK_EQ(Weight(3.0), Plus(Weight::Zero(), 3.0f));
CHECK_EQ(Weight(3.0), Plus(Weight::Zero(), 3.0));
CHECK_EQ(Weight(3.0), Plus(3.0, Weight::Zero()));
}
void TestPowerWeightGetSetValue() {
PowerWeight<LogWeight, 3> w;
// LogWeight has unspecified initial value, so don't check it.
w.SetValue(0, LogWeight(2));
w.SetValue(1, LogWeight(3));
CHECK_EQ(LogWeight(2), w.Value(0));
CHECK_EQ(LogWeight(3), w.Value(1));
}
void TestSparsePowerWeightGetSetValue() {
const LogWeight default_value(17);
SparsePowerWeight<LogWeight> w;
w.SetDefaultValue(default_value);
// All gets should be the default.
CHECK_EQ(default_value, w.Value(0));
CHECK_EQ(default_value, w.Value(100));
// First set should fill first_.
w.SetValue(10, LogWeight(10));
CHECK_EQ(LogWeight(10), w.Value(10));
w.SetValue(10, LogWeight(20));
CHECK_EQ(LogWeight(20), w.Value(10));
// Add a smaller index.
w.SetValue(5, LogWeight(5));
CHECK_EQ(LogWeight(5), w.Value(5));
CHECK_EQ(LogWeight(20), w.Value(10));
// Add some larger indices.
w.SetValue(30, LogWeight(30));
CHECK_EQ(LogWeight(5), w.Value(5));
CHECK_EQ(LogWeight(20), w.Value(10));
CHECK_EQ(LogWeight(30), w.Value(30));
w.SetValue(29, LogWeight(29));
CHECK_EQ(LogWeight(5), w.Value(5));
CHECK_EQ(LogWeight(20), w.Value(10));
CHECK_EQ(LogWeight(29), w.Value(29));
CHECK_EQ(LogWeight(30), w.Value(30));
w.SetValue(31, LogWeight(31));
CHECK_EQ(LogWeight(5), w.Value(5));
CHECK_EQ(LogWeight(20), w.Value(10));
CHECK_EQ(LogWeight(29), w.Value(29));
CHECK_EQ(LogWeight(30), w.Value(30));
CHECK_EQ(LogWeight(31), w.Value(31));
// Replace a value.
w.SetValue(30, LogWeight(60));
CHECK_EQ(LogWeight(60), w.Value(30));
// Replace a value with the default.
CHECK_EQ(5, w.Size());
w.SetValue(30, default_value);
CHECK_EQ(default_value, w.Value(30));
CHECK_EQ(4, w.Size());
// Replace lowest index by the default value.
w.SetValue(5, default_value);
CHECK_EQ(default_value, w.Value(5));
CHECK_EQ(3, w.Size());
// Clear out everything.
w.SetValue(31, default_value);
w.SetValue(29, default_value);
w.SetValue(10, default_value);
CHECK_EQ(0, w.Size());
CHECK_EQ(default_value, w.Value(5));
CHECK_EQ(default_value, w.Value(10));
CHECK_EQ(default_value, w.Value(29));
CHECK_EQ(default_value, w.Value(30));
CHECK_EQ(default_value, w.Value(31));
}
} // namespace
int main(int argc, char **argv) {
std::set_new_handler(FailedNewHandler);
SET_FLAGS(argv[0], &argc, &argv, true);
LOG(INFO) << "Seed = " << FLAGS_seed;
srand(FLAGS_seed);
TestTemplatedWeights<float>(FLAGS_repeat);
TestTemplatedWeights<double>(FLAGS_repeat);
FLAGS_fst_weight_parentheses = "()";
TestTemplatedWeights<float>(FLAGS_repeat);
TestTemplatedWeights<double>(FLAGS_repeat);
FLAGS_fst_weight_parentheses = "";
// Makes sure type names for templated weights are consistent.
CHECK(TropicalWeight::Type() == "tropical");
CHECK(TropicalWeightTpl<double>::Type() != TropicalWeightTpl<float>::Type());
CHECK(LogWeight::Type() == "log");
CHECK(LogWeightTpl<double>::Type() != LogWeightTpl<float>::Type());
TropicalWeightTpl<double> w(2.0);
TropicalWeight tw(2.0);
TestAdder<TropicalWeight>(1000);
TestAdder<LogWeight>(1000);
TestSignedAdder<SignedLogWeight>(1000);
TestImplicitConversion<LogWeight>();
TestImplicitConversion<TropicalWeight>();
TestImplicitConversion<MinMaxWeight>();
TestWeightConversion<TropicalWeight, LogWeight>(2.0);
using LeftStringWeight = StringWeight<int>;
using LeftStringWeightGenerate = WeightGenerate<LeftStringWeight>;
LeftStringWeightGenerate left_string_generate;
WeightTester<LeftStringWeight, LeftStringWeightGenerate> left_string_tester(
left_string_generate);
left_string_tester.Test(FLAGS_repeat);
using RightStringWeight = StringWeight<int, STRING_RIGHT>;
using RightStringWeightGenerate = WeightGenerate<RightStringWeight>;
RightStringWeightGenerate right_string_generate;
WeightTester<RightStringWeight, RightStringWeightGenerate>
right_string_tester(right_string_generate);
right_string_tester.Test(FLAGS_repeat);
// STRING_RESTRICT not tested since it requires equal strings,
// so would fail.
using IUSetWeight = SetWeight<int, SET_INTERSECT_UNION>;
using IUSetWeightGenerate = WeightGenerate<IUSetWeight>;
IUSetWeightGenerate iu_set_generate;
WeightTester<IUSetWeight, IUSetWeightGenerate>
iu_set_tester(iu_set_generate);
iu_set_tester.Test(FLAGS_repeat);
using UISetWeight = SetWeight<int, SET_UNION_INTERSECT>;
using UISetWeightGenerate = WeightGenerate<UISetWeight>;
UISetWeightGenerate ui_set_generate;
WeightTester<UISetWeight, UISetWeightGenerate>
ui_set_tester(ui_set_generate);
ui_set_tester.Test(FLAGS_repeat);
// SET_INTERSECT_UNION_RESTRICT not tested since it requires equal sets,
// so would fail.
using BoolSetWeight = SetWeight<int, SET_BOOLEAN>;
using BoolSetWeightGenerate = WeightGenerate<BoolSetWeight>;
BoolSetWeightGenerate bool_set_generate;
WeightTester<BoolSetWeight, BoolSetWeightGenerate>
bool_set_tester(bool_set_generate);
bool_set_tester.Test(FLAGS_repeat);
TestWeightConversion<IUSetWeight, UISetWeight>(iu_set_generate());
TestWeightCopy<IUSetWeight, UISetWeight>(iu_set_generate());
TestWeightCopy<IUSetWeight, BoolSetWeight>(iu_set_generate());
TestWeightCopy<UISetWeight, IUSetWeight>(ui_set_generate());
TestWeightCopy<UISetWeight, BoolSetWeight>(ui_set_generate());
TestWeightCopy<BoolSetWeight, IUSetWeight>(bool_set_generate());
TestWeightCopy<BoolSetWeight, UISetWeight>(bool_set_generate());
TestWeightMove<IUSetWeight, UISetWeight>(iu_set_generate());
TestWeightMove<IUSetWeight, BoolSetWeight>(iu_set_generate());
TestWeightMove<UISetWeight, IUSetWeight>(ui_set_generate());
TestWeightMove<UISetWeight, BoolSetWeight>(ui_set_generate());
TestWeightMove<BoolSetWeight, IUSetWeight>(bool_set_generate());
TestWeightMove<BoolSetWeight, UISetWeight>(bool_set_generate());
// COMPOSITE WEIGHTS AND TESTERS - DEFINITIONS
using TropicalGallicWeight = GallicWeight<int, TropicalWeight>;
using TropicalGallicWeightGenerate = WeightGenerate<TropicalGallicWeight>;
TropicalGallicWeightGenerate tropical_gallic_generate(true);
WeightTester<TropicalGallicWeight, TropicalGallicWeightGenerate>
tropical_gallic_tester(tropical_gallic_generate);
using TropicalGenGallicWeight = GallicWeight<int, TropicalWeight, GALLIC>;
using TropicalGenGallicWeightGenerate =
WeightGenerate<TropicalGenGallicWeight>;
TropicalGenGallicWeightGenerate tropical_gen_gallic_generate(false);
WeightTester<TropicalGenGallicWeight, TropicalGenGallicWeightGenerate>
tropical_gen_gallic_tester(tropical_gen_gallic_generate);
using TropicalProductWeight = ProductWeight<TropicalWeight, TropicalWeight>;
using TropicalProductWeightGenerate = WeightGenerate<TropicalProductWeight>;
TropicalProductWeightGenerate tropical_product_generate;
WeightTester<TropicalProductWeight, TropicalProductWeightGenerate>
tropical_product_tester(tropical_product_generate);
using TropicalLexicographicWeight =
LexicographicWeight<TropicalWeight, TropicalWeight>;
using TropicalLexicographicWeightGenerate =
WeightGenerate<TropicalLexicographicWeight>;
TropicalLexicographicWeightGenerate tropical_lexicographic_generate;
WeightTester<TropicalLexicographicWeight,
TropicalLexicographicWeightGenerate>
tropical_lexicographic_tester(tropical_lexicographic_generate);
using TropicalCubeWeight = PowerWeight<TropicalWeight, 3>;
using TropicalCubeWeightGenerate = WeightGenerate<TropicalCubeWeight>;
TropicalCubeWeightGenerate tropical_cube_generate;
WeightTester<TropicalCubeWeight, TropicalCubeWeightGenerate>
tropical_cube_tester(tropical_cube_generate);
using FirstNestedProductWeight =
ProductWeight<TropicalProductWeight, TropicalWeight>;
using FirstNestedProductWeightGenerate =
WeightGenerate<FirstNestedProductWeight>;
FirstNestedProductWeightGenerate first_nested_product_generate;
WeightTester<FirstNestedProductWeight, FirstNestedProductWeightGenerate>
first_nested_product_tester(first_nested_product_generate);
using SecondNestedProductWeight =
ProductWeight<TropicalWeight, TropicalProductWeight>;
using SecondNestedProductWeightGenerate =
WeightGenerate<SecondNestedProductWeight>;
SecondNestedProductWeightGenerate second_nested_product_generate;
WeightTester<SecondNestedProductWeight, SecondNestedProductWeightGenerate>
second_nested_product_tester(second_nested_product_generate);
using NestedProductCubeWeight = PowerWeight<FirstNestedProductWeight, 3>;
using NestedProductCubeWeightGenerate =
WeightGenerate<NestedProductCubeWeight>;
NestedProductCubeWeightGenerate nested_product_cube_generate;
WeightTester<NestedProductCubeWeight, NestedProductCubeWeightGenerate>
nested_product_cube_tester(nested_product_cube_generate);
using SparseNestedProductCubeWeight =
SparsePowerWeight<NestedProductCubeWeight, size_t>;
using SparseNestedProductCubeWeightGenerate =
WeightGenerate<SparseNestedProductCubeWeight>;
SparseNestedProductCubeWeightGenerate sparse_nested_product_cube_generate;
WeightTester<SparseNestedProductCubeWeight,
SparseNestedProductCubeWeightGenerate>
sparse_nested_product_cube_tester(sparse_nested_product_cube_generate);
using LogSparsePowerWeight = SparsePowerWeight<LogWeight, size_t>;
using LogSparsePowerWeightGenerate = WeightGenerate<LogSparsePowerWeight>;
LogSparsePowerWeightGenerate log_sparse_power_generate;
WeightTester<LogSparsePowerWeight, LogSparsePowerWeightGenerate>
log_sparse_power_tester(log_sparse_power_generate);
using LogLogExpectationWeight = ExpectationWeight<LogWeight, LogWeight>;
using LogLogExpectationWeightGenerate =
WeightGenerate<LogLogExpectationWeight>;
LogLogExpectationWeightGenerate log_log_expectation_generate;
WeightTester<LogLogExpectationWeight, LogLogExpectationWeightGenerate>
log_log_expectation_tester(log_log_expectation_generate);
using LogLogSparseExpectationWeight =
ExpectationWeight<LogWeight, LogSparsePowerWeight>;
using LogLogSparseExpectationWeightGenerate =
WeightGenerate<LogLogSparseExpectationWeight>;
LogLogSparseExpectationWeightGenerate log_log_sparse_expectation_generate;
WeightTester<LogLogSparseExpectationWeight,
LogLogSparseExpectationWeightGenerate>
log_log_sparse_expectation_tester(log_log_sparse_expectation_generate);
struct UnionWeightOptions {
using Compare = NaturalLess<TropicalWeight>;
struct Merge {
TropicalWeight operator()(const TropicalWeight &w1,
const TropicalWeight &w2) const {
return w1;
}
};
using ReverseOptions = UnionWeightOptions;
};
using TropicalUnionWeight = UnionWeight<TropicalWeight, UnionWeightOptions>;
using TropicalUnionWeightGenerate = WeightGenerate<TropicalUnionWeight>;
TropicalUnionWeightGenerate tropical_union_generate;
WeightTester<TropicalUnionWeight, TropicalUnionWeightGenerate>
tropical_union_tester(tropical_union_generate);
// COMPOSITE WEIGHTS AND TESTERS - TESTING
// Tests composite weight I/O with parentheses.
FLAGS_fst_weight_parentheses = "()";
// Unnested composite.
tropical_gallic_tester.Test(FLAGS_repeat);
tropical_gen_gallic_tester.Test(FLAGS_repeat);
tropical_product_tester.Test(FLAGS_repeat);
tropical_lexicographic_tester.Test(FLAGS_repeat);
tropical_cube_tester.Test(FLAGS_repeat);
log_sparse_power_tester.Test(FLAGS_repeat);
log_log_expectation_tester.Test(FLAGS_repeat, false);
tropical_union_tester.Test(FLAGS_repeat, false);
// Nested composite.
first_nested_product_tester.Test(FLAGS_repeat);
second_nested_product_tester.Test(5);
nested_product_cube_tester.Test(FLAGS_repeat);
sparse_nested_product_cube_tester.Test(FLAGS_repeat);
log_log_sparse_expectation_tester.Test(FLAGS_repeat, false);
// ... and tests composite weight I/O without parentheses.
FLAGS_fst_weight_parentheses = "";
// Unnested composite.
tropical_gallic_tester.Test(FLAGS_repeat);
tropical_product_tester.Test(FLAGS_repeat);
tropical_lexicographic_tester.Test(FLAGS_repeat);
tropical_cube_tester.Test(FLAGS_repeat);
log_sparse_power_tester.Test(FLAGS_repeat);
log_log_expectation_tester.Test(FLAGS_repeat, false);
tropical_union_tester.Test(FLAGS_repeat, false);
// Nested composite.
second_nested_product_tester.Test(FLAGS_repeat);
log_log_sparse_expectation_tester.Test(FLAGS_repeat, false);
TestPowerWeightGetSetValue();
TestSparsePowerWeightGetSetValue();
std::cout << "PASS" << std::endl;
return 0;
}
| 0 |
coqui_public_repos/STT/training/coqui_stt_training | coqui_public_repos/STT/training/coqui_stt_training/util/multiprocessing.py | #!/usr/bin/env python
import multiprocessing
import multiprocessing.pool
import os
import sys
from contextlib import contextmanager
def target_fn(*args, **kwargs):
return target_impl.run(*args, **kwargs)
def target_fn_single(arg):
return target_impl.run(arg)
def init_fn(target_impl_cls, global_lock, parent_env, id_queue, initargs):
process_id = id_queue.get()
global target_impl
target_impl = target_impl_cls()
target_impl._child_init(global_lock, process_id)
child_env = target_impl.get_child_env(parent_env)
if child_env is not None:
os.environ = child_env
target_impl.init(*initargs)
class PoolBase:
"""Object oriented wrapper around multiprocessing.pool.Pool.
Users should subclass this class and implement the `run` method, and
optionally the `init` method.
`init` will be called, in the child process, once per process. In your
implementation you can use `self.lock` which is a lock object shared accross
all child processes in order to synchronize work between all processes. You
can also use `self.process_id`, which is an integer, unique per process,
increasing in value from 0 to processes-1 (if not specified, processes
defaults to os.cpu_count()).
`run` will be called, in the child processes, potentially multiple times, in
order to process data.
You can then use the `create` classmethod to create a new Pool object, which
can then be used with the usual multiprocessing.pool.Pool methods (eg. map,
imap, imap_unordered, etc).
Example usage:
class MultiplyByTwoPool(PoolBase):
def init(self, pool_name):
with self.lock:
print(f"[{pool_name}] synchronized step in proc {self.process_id}")
def get_child_env(self, parent_env):
parent_env["TEST_VAR"] = str(self.process_id)
return parent_env
def run(self, x):
assert os.environ["TEST_VAR"] == str(self.process_id)
return x*2
pool = MultiplyByTwoPool.create(processes=4, initargs=("my pool",))
print(pool.map(range(10)))
"""
@classmethod
def create_impl(cls, processes=None, context=None, initargs=(), *args, **kwargs):
if processes is None:
processes = os.cpu_count()
if context is None:
context = multiprocessing
queue = context.Queue()
for i in range(processes):
queue.put(i)
lock = context.Lock()
parent_env = os.environ.copy()
pool = cls()
pool._inner_pool = multiprocessing.pool.Pool(
processes=processes,
initializer=init_fn,
initargs=(cls, lock, parent_env, queue, initargs),
context=context,
*args,
**kwargs,
)
return pool
@classmethod
@contextmanager
def create(cls, processes=None, context=None, initargs=(), *args, **kwargs):
pool = cls.create_impl(processes, context, initargs, *args, **kwargs)
try:
yield pool
finally:
pool._inner_pool.close()
def _child_init(self, lock, process_id):
self.lock = lock
self.process_id = process_id
def init(self, *args):
pass
def run(self, *args, **kwargs):
raise NotImplementedError()
def get_child_env(self, parent_env):
return None
def apply(self, *args, **kwargs):
return self._inner_pool.apply(target_fn, *args, **kwargs)
def apply_async(self, *args, **kwargs):
return self._inner_pool.apply_async(target_fn, *args, **kwargs)
def map(self, *args, **kwargs):
return self._inner_pool.map(target_fn, *args, **kwargs)
def map_async(self, *args, **kwargs):
return self._inner_pool.map_async(target_fn, *args, **kwargs)
def imap(self, *args, **kwargs):
return self._inner_pool.imap(target_fn, *args, **kwargs)
def imap_unordered(self, *args, **kwargs):
return self._inner_pool.imap_unordered(target_fn, *args, **kwargs)
def starmap(self, *args, **kwargs):
return self._inner_pool.starmap(target_fn, *args, **kwargs)
def starmap_async(self, *args, **kwargs):
return self._inner_pool.starmap_async(target_fn, *args, **kwargs)
def close(self):
return self._inner_pool.close()
def terminate(self):
return self._inner_pool.terminate()
def join(self):
return self._inner_pool.join()
if __name__ == "__main__":
class MultiplyByTwoPool(PoolBase):
def init(self):
with self.lock:
print(f"synchronized step in proc {self.process_id}")
def get_child_env(self, parent_env):
parent_env["TEST_VAR"] = str(self.process_id)
return parent_env
def run(self, x):
assert os.environ["TEST_VAR"] == str(self.process_id)
return x * 2
pool = MultiplyByTwoPool.create(processes=4)
print(pool.apply((2,)))
print(pool.map(range(10)))
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/product-weight.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Product weight set and associated semiring operation definitions.
#ifndef FST_PRODUCT_WEIGHT_H_
#define FST_PRODUCT_WEIGHT_H_
#include <string>
#include <utility>
#include <fst/pair-weight.h>
#include <fst/weight.h>
namespace fst {
// Product semiring: W1 * W2.
template <class W1, class W2>
class ProductWeight : public PairWeight<W1, W2> {
public:
using ReverseWeight =
ProductWeight<typename W1::ReverseWeight, typename W2::ReverseWeight>;
ProductWeight() {}
explicit ProductWeight(const PairWeight<W1, W2> &weight)
: PairWeight<W1, W2>(weight) {}
ProductWeight(W1 w1, W2 w2)
: PairWeight<W1, W2>(std::move(w1), std::move(w2)) {}
static const ProductWeight &Zero() {
static const ProductWeight zero(PairWeight<W1, W2>::Zero());
return zero;
}
static const ProductWeight &One() {
static const ProductWeight one(PairWeight<W1, W2>::One());
return one;
}
static const ProductWeight &NoWeight() {
static const ProductWeight no_weight(PairWeight<W1, W2>::NoWeight());
return no_weight;
}
static const string &Type() {
static const string *const type =
new string(W1::Type() + "_X_" + W2::Type());
return *type;
}
static constexpr uint64_t Properties() {
return W1::Properties() & W2::Properties() &
(kLeftSemiring | kRightSemiring | kCommutative | kIdempotent);
}
ProductWeight Quantize(float delta = kDelta) const {
return ProductWeight(PairWeight<W1, W2>::Quantize(delta));
}
ReverseWeight Reverse() const {
return ReverseWeight(PairWeight<W1, W2>::Reverse());
}
};
template <class W1, class W2>
inline ProductWeight<W1, W2> Plus(const ProductWeight<W1, W2> &w1,
const ProductWeight<W1, W2> &w2) {
return ProductWeight<W1, W2>(Plus(w1.Value1(), w2.Value1()),
Plus(w1.Value2(), w2.Value2()));
}
template <class W1, class W2>
inline ProductWeight<W1, W2> Times(const ProductWeight<W1, W2> &w1,
const ProductWeight<W1, W2> &w2) {
return ProductWeight<W1, W2>(Times(w1.Value1(), w2.Value1()),
Times(w1.Value2(), w2.Value2()));
}
template <class W1, class W2>
inline ProductWeight<W1, W2> Divide(const ProductWeight<W1, W2> &w1,
const ProductWeight<W1, W2> &w2,
DivideType typ = DIVIDE_ANY) {
return ProductWeight<W1, W2>(Divide(w1.Value1(), w2.Value1(), typ),
Divide(w1.Value2(), w2.Value2(), typ));
}
// This function object generates weights by calling the underlying generators
// for the template weight types, like all other pair weight types. This is
// intended primarily for testing.
template <class W1, class W2>
class WeightGenerate<ProductWeight<W1, W2>> :
public WeightGenerate<PairWeight<W1, W2>> {
public:
using Weight = ProductWeight<W1, W2>;
using Generate = WeightGenerate<PairWeight<W1, W2>>;
explicit WeightGenerate(bool allow_zero = true) : Generate(allow_zero) {}
Weight operator()() const { return Weight(Generate::operator()()); }
};
} // namespace fst
#endif // FST_PRODUCT_WEIGHT_H_
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/bin/fsttopsort-main.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Topologically sorts an FST.
#include <cstring>
#include <memory>
#include <string>
#include <fst/flags.h>
#include <fst/log.h>
#include <fst/script/topsort.h>
int fsttopsort_main(int argc, char **argv) {
namespace s = fst::script;
using fst::script::MutableFstClass;
string usage = "Topologically sorts an FST.\n\n Usage: ";
usage += argv[0];
usage += " [in.fst [out.fst]]\n";
std::set_new_handler(FailedNewHandler);
SET_FLAGS(usage.c_str(), &argc, &argv, true);
if (argc > 3) {
ShowUsage();
return 1;
}
const string in_name = argc > 1 && strcmp(argv[1], "-") != 0 ? argv[1] : "";
const string out_name = argc > 2 ? argv[2] : "";
std::unique_ptr<MutableFstClass> fst(MutableFstClass::Read(in_name, true));
if (!fst) return 1;
bool acyclic = TopSort(fst.get());
if (!acyclic) LOG(WARNING) << argv[0] << ": Input FST is cyclic";
return !fst->Write(out_name);
}
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/lookahead-matcher.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Classes to add lookahead to FST matchers, useful for improving composition
// efficiency with certain inputs.
#ifndef FST_LOOKAHEAD_MATCHER_H_
#define FST_LOOKAHEAD_MATCHER_H_
#include <memory>
#include <utility>
#include <vector>
#include <fst/flags.h>
#include <fst/log.h>
#include <fst/add-on.h>
#include <fst/const-fst.h>
#include <fst/fst.h>
#include <fst/label-reachable.h>
#include <fst/matcher.h>
DECLARE_string(save_relabel_ipairs);
DECLARE_string(save_relabel_opairs);
namespace fst {
// Lookahead matches extend the matcher interface with following additional
// methods:
//
// template <class FST>
// class LookAheadMatcher {
// public:
// using Arc = typename FST::Arc;
// using Label = typename Arc::Label;
// using StateId = typename Arc::StateId;
// using Weight = typename Arc::Weight;
//
// // Required constructors.
// // This makes a copy of the FST.
// LookAheadMatcher(const FST &fst, MatchType match_type);
// // This doesn't copy the FST.
// LookAheadMatcher(const FST *fst, MatchType match_type);
// // This makes a copy of the FST.
// // See Copy() below.
// LookAheadMatcher(const LookAheadMatcher &matcher, bool safe = false);
//
// // If safe = true, the copy is thread-safe (except the lookahead FST is
// // preserved). See Fst<>::Copy() for further doc.
// LookaheadMatcher<FST> *Copy(bool safe = false) const override;
// // Below are methods for looking ahead for a match to a label and more
// // generally, to a rational set. Each returns false if there is definitely
// // not a match and returns true if there possibly is a match.
//
// // Optionally pre-specifies the lookahead FST that will be passed to
// // LookAheadFst() for possible precomputation. If copy is true, then the FST
// // argument is a copy of the FST used in the previous call to this method
// // (to avoid unnecessary updates).
// void InitLookAheadFst(const Fst<Arc> &fst, bool copy = false) override;
//
// // Are there paths from a state in the lookahead FST that can be read from
// // the curent matcher state?
// bool LookAheadFst(const Fst<Arc> &fst, StateId s) override;
//
// // Can the label be read from the current matcher state after possibly
// // following epsilon transitions?
// bool LookAheadLabel(Label label) const override;
//
// // The following methods allow looking ahead for an arbitrary rational set
// // of strings, specified by an FST and a state from which to begin the
// // matching. If the lookahead FST is a transducer, this looks on the side
// // different from the matcher's match_type (cf. composition).
// // Is there is a single non-epsilon arc found in the lookahead FST that
// // begins the path (after possibly following any epsilons) in the last call
// // to LookAheadFst? If so, return true and copy it to the arc argument;
// // otherwise, return false. Non-trivial implementations are useful for
// // label-pushing in composition.
// bool LookAheadPrefix(Arc *arc) override;
//
// // Gives an estimate of the combined weight of the paths in the lookahead
// // and matcher FSTs for the last call to LookAheadFst. Non-trivial
// // implementations are useful for weight-pushing in composition.
// Weight LookAheadWeight() const override;
// };
// Look-ahead flags.
// Matcher is a lookahead matcher when match_type is MATCH_INPUT.
constexpr uint32 kInputLookAheadMatcher = 0x00000010;
// Matcher is a lookahead matcher when match_type is MATCH_OUTPUT.
constexpr uint32 kOutputLookAheadMatcher = 0x00000020;
// Is a non-trivial implementation of LookAheadWeight() method defined and
// if so, should it be used?
constexpr uint32 kLookAheadWeight = 0x00000040;
// Is a non-trivial implementation of LookAheadPrefix() method defined and
// if so, should it be used?
constexpr uint32 kLookAheadPrefix = 0x00000080;
// Look-ahead of matcher FST non-epsilon arcs?
constexpr uint32 kLookAheadNonEpsilons = 0x00000100;
// Look-ahead of matcher FST epsilon arcs?
constexpr uint32 kLookAheadEpsilons = 0x00000200;
// Ignore epsilon paths for the lookahead prefix? This gives correct results in
// composition only with an appropriate composition filter since it depends on
// the filter blocking the ignored paths.
constexpr uint32 kLookAheadNonEpsilonPrefix = 0x00000400;
// For LabelLookAheadMatcher, save relabeling data to file?
constexpr uint32 kLookAheadKeepRelabelData = 0x00000800;
// Flags used for lookahead matchers.
constexpr uint32 kLookAheadFlags = 0x00000ff0;
// LookAhead Matcher interface, templated on the Arc definition; used
// for lookahead matcher specializations that are returned by the
// InitMatcher() Fst method.
template <class Arc>
class LookAheadMatcherBase : public MatcherBase<Arc> {
public:
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
virtual void InitLookAheadFst(const Fst<Arc> &, bool copy = false) = 0;
virtual bool LookAheadFst(const Fst<Arc> &, StateId) = 0;
virtual bool LookAheadLabel(Label) const = 0;
// Suggested concrete implementation of lookahead methods.
bool LookAheadPrefix(Arc *arc) const {
if (prefix_arc_.nextstate != kNoStateId) {
*arc = prefix_arc_;
return true;
} else {
return false;
}
}
Weight LookAheadWeight() const { return weight_; }
protected:
// Concrete implementations for lookahead helper methods.
void ClearLookAheadWeight() { weight_ = Weight::One(); }
void SetLookAheadWeight(Weight weight) { weight_ = std::move(weight); }
void ClearLookAheadPrefix() { prefix_arc_.nextstate = kNoStateId; }
void SetLookAheadPrefix(Arc arc) { prefix_arc_ = std::move(arc); }
private:
Arc prefix_arc_;
Weight weight_;
};
// Doesn't actually lookahead, just declares that the future looks good.
template <class M>
class TrivialLookAheadMatcher
: public LookAheadMatcherBase<typename M::FST::Arc> {
public:
using FST = typename M::FST;
using Arc = typename FST::Arc;
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
// This makes a copy of the FST.
TrivialLookAheadMatcher(const FST &fst, MatchType match_type)
: matcher_(fst, match_type) {}
// This doesn't copy the FST.
TrivialLookAheadMatcher(const FST *fst, MatchType match_type)
: matcher_(fst, match_type) {}
// This makes a copy of the FST.
TrivialLookAheadMatcher(const TrivialLookAheadMatcher<M> &lmatcher,
bool safe = false)
: matcher_(lmatcher.matcher_, safe) {}
TrivialLookAheadMatcher<M> *Copy(bool safe = false) const override {
return new TrivialLookAheadMatcher<M>(*this, safe);
}
MatchType Type(bool test) const override { return matcher_.Type(test); }
void SetState(StateId s) final { return matcher_.SetState(s); }
bool Find(Label label) final { return matcher_.Find(label); }
bool Done() const final { return matcher_.Done(); }
const Arc &Value() const final { return matcher_.Value(); }
void Next() final { matcher_.Next(); }
Weight Final(StateId s) const final { return matcher_.Final(s); }
ssize_t Priority(StateId s) final { return matcher_.Priority(s); }
const FST &GetFst() const override { return matcher_.GetFst(); }
uint64 Properties(uint64 props) const override {
return matcher_.Properties(props);
}
uint32 Flags() const override {
return matcher_.Flags() | kInputLookAheadMatcher | kOutputLookAheadMatcher;
}
// Lookahead methods (all trivial).
void InitLookAheadFst(const Fst<Arc> &fst, bool copy = false) override {}
bool LookAheadFst(const Fst<Arc> &, StateId) final { return true; }
bool LookAheadLabel(Label) const final { return true; }
bool LookAheadPrefix(Arc *) const { return false; }
Weight LookAheadWeight() const { return Weight::One(); }
private:
M matcher_;
};
// Look-ahead of one transition. Template argument flags accepts flags to
// control behavior.
template <class M,
uint32 flags = kLookAheadNonEpsilons | kLookAheadEpsilons |
kLookAheadWeight | kLookAheadPrefix>
class ArcLookAheadMatcher : public LookAheadMatcherBase<typename M::FST::Arc> {
public:
using FST = typename M::FST;
using Arc = typename FST::Arc;
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
using MatcherData = NullAddOn;
using LookAheadMatcherBase<Arc>::ClearLookAheadWeight;
using LookAheadMatcherBase<Arc>::LookAheadWeight;
using LookAheadMatcherBase<Arc>::SetLookAheadWeight;
using LookAheadMatcherBase<Arc>::ClearLookAheadPrefix;
using LookAheadMatcherBase<Arc>::LookAheadPrefix;
using LookAheadMatcherBase<Arc>::SetLookAheadPrefix;
enum : uint32 { kFlags = flags };
// This makes a copy of the FST.
ArcLookAheadMatcher(
const FST &fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::shared_ptr<MatcherData>())
: matcher_(fst, match_type),
fst_(matcher_.GetFst()),
lfst_(nullptr),
state_(kNoStateId) {}
// This doesn't copy the FST.
ArcLookAheadMatcher(
const FST *fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::shared_ptr<MatcherData>())
: matcher_(fst, match_type),
fst_(matcher_.GetFst()),
lfst_(nullptr),
state_(kNoStateId) {}
// This makes a copy of the FST.
ArcLookAheadMatcher(const ArcLookAheadMatcher<M, flags> &lmatcher,
bool safe = false)
: matcher_(lmatcher.matcher_, safe),
fst_(matcher_.GetFst()),
lfst_(lmatcher.lfst_),
state_(kNoStateId) {}
// General matcher methods.
ArcLookAheadMatcher<M, flags> *Copy(bool safe = false) const override {
return new ArcLookAheadMatcher<M, flags>(*this, safe);
}
MatchType Type(bool test) const override { return matcher_.Type(test); }
void SetState(StateId s) final {
state_ = s;
matcher_.SetState(s);
}
bool Find(Label label) final { return matcher_.Find(label); }
bool Done() const final { return matcher_.Done(); }
const Arc &Value() const final { return matcher_.Value(); }
void Next() final { matcher_.Next(); }
Weight Final(StateId s) const final { return matcher_.Final(s); }
ssize_t Priority(StateId s) final { return matcher_.Priority(s); }
const FST &GetFst() const override { return fst_; }
uint64 Properties(uint64 props) const override {
return matcher_.Properties(props);
}
uint32 Flags() const override {
return matcher_.Flags() | kInputLookAheadMatcher | kOutputLookAheadMatcher |
kFlags;
}
const MatcherData *GetData() const { return nullptr; }
std::shared_ptr<MatcherData> GetSharedData() const {
return std::shared_ptr<MatcherData>();
}
// Look-ahead methods.
void InitLookAheadFst(const Fst<Arc> &fst, bool copy = false) override {
lfst_ = &fst;
}
// Checks if there is a matching (possibly super-final) transition
// at (state_, s).
bool LookAheadFst(const Fst<Arc> &, StateId) final;
bool LookAheadLabel(Label label) const final { return matcher_.Find(label); }
private:
mutable M matcher_;
const FST &fst_; // Matcher FST.
const Fst<Arc> *lfst_; // Look-ahead FST.
StateId state_; // Matcher state.
};
template <class M, uint32 flags>
bool ArcLookAheadMatcher<M, flags>::LookAheadFst(const Fst<Arc> &fst,
StateId s) {
if (&fst != lfst_) InitLookAheadFst(fst);
bool result = false;
ssize_t nprefix = 0;
if (kFlags & kLookAheadWeight) ClearLookAheadWeight();
if (kFlags & kLookAheadPrefix) ClearLookAheadPrefix();
if (fst_.Final(state_) != Weight::Zero() &&
lfst_->Final(s) != Weight::Zero()) {
if (!(kFlags & (kLookAheadWeight | kLookAheadPrefix))) return true;
++nprefix;
if (kFlags & kLookAheadWeight) {
SetLookAheadWeight(
Plus(LookAheadWeight(), Times(fst_.Final(state_), lfst_->Final(s))));
}
result = true;
}
if (matcher_.Find(kNoLabel)) {
if (!(kFlags & (kLookAheadWeight | kLookAheadPrefix))) return true;
++nprefix;
if (kFlags & kLookAheadWeight) {
for (; !matcher_.Done(); matcher_.Next()) {
SetLookAheadWeight(Plus(LookAheadWeight(), matcher_.Value().weight));
}
}
result = true;
}
for (ArcIterator<Fst<Arc>> aiter(*lfst_, s); !aiter.Done(); aiter.Next()) {
const auto &arc = aiter.Value();
Label label = kNoLabel;
switch (matcher_.Type(false)) {
case MATCH_INPUT:
label = arc.olabel;
break;
case MATCH_OUTPUT:
label = arc.ilabel;
break;
default:
FSTERROR() << "ArcLookAheadMatcher::LookAheadFst: Bad match type";
return true;
}
if (label == 0) {
if (!(kFlags & (kLookAheadWeight | kLookAheadPrefix))) return true;
if (!(kFlags & kLookAheadNonEpsilonPrefix)) ++nprefix;
if (kFlags & kLookAheadWeight) {
SetLookAheadWeight(Plus(LookAheadWeight(), arc.weight));
}
result = true;
} else if (matcher_.Find(label)) {
if (!(kFlags & (kLookAheadWeight | kLookAheadPrefix))) return true;
for (; !matcher_.Done(); matcher_.Next()) {
++nprefix;
if (kFlags & kLookAheadWeight) {
SetLookAheadWeight(Plus(LookAheadWeight(),
Times(arc.weight, matcher_.Value().weight)));
}
if ((kFlags & kLookAheadPrefix) && nprefix == 1)
SetLookAheadPrefix(arc);
}
result = true;
}
}
if (kFlags & kLookAheadPrefix) {
if (nprefix == 1) {
ClearLookAheadWeight(); // Avoids double counting.
} else {
ClearLookAheadPrefix();
}
}
return result;
}
// Template argument flags accepts flags to control behavior. It must include
// precisely one of kInputLookAheadMatcher or kOutputLookAheadMatcher.
template <class M,
uint32 flags = kLookAheadEpsilons | kLookAheadWeight |
kLookAheadPrefix | kLookAheadNonEpsilonPrefix |
kLookAheadKeepRelabelData,
class Accumulator = DefaultAccumulator<typename M::Arc>,
class Reachable = LabelReachable<typename M::Arc, Accumulator>>
class LabelLookAheadMatcher
: public LookAheadMatcherBase<typename M::FST::Arc> {
public:
using FST = typename M::FST;
using Arc = typename FST::Arc;
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
using MatcherData = typename Reachable::Data;
using LookAheadMatcherBase<Arc>::ClearLookAheadWeight;
using LookAheadMatcherBase<Arc>::LookAheadWeight;
using LookAheadMatcherBase<Arc>::SetLookAheadWeight;
using LookAheadMatcherBase<Arc>::ClearLookAheadPrefix;
using LookAheadMatcherBase<Arc>::LookAheadPrefix;
using LookAheadMatcherBase<Arc>::SetLookAheadPrefix;
enum : uint32 { kFlags = flags };
// This makes a copy of the FST.
LabelLookAheadMatcher(
const FST &fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::shared_ptr<MatcherData>(),
Accumulator *accumulator = nullptr)
: matcher_(fst, match_type),
lfst_(nullptr),
state_(kNoStateId),
error_(false) {
Init(fst, match_type, data, accumulator);
}
// This doesn't copy the FST.
LabelLookAheadMatcher(
const FST *fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::shared_ptr<MatcherData>(),
Accumulator *accumulator = nullptr)
: matcher_(fst, match_type),
lfst_(nullptr),
state_(kNoStateId),
error_(false) {
Init(*fst, match_type, data, accumulator);
}
// This makes a copy of the FST.
LabelLookAheadMatcher(
const LabelLookAheadMatcher<M, flags, Accumulator, Reachable> &lmatcher,
bool safe = false)
: matcher_(lmatcher.matcher_, safe),
lfst_(lmatcher.lfst_),
label_reachable_(lmatcher.label_reachable_
? new Reachable(*lmatcher.label_reachable_, safe)
: nullptr),
state_(kNoStateId),
error_(lmatcher.error_) {}
LabelLookAheadMatcher<M, flags, Accumulator, Reachable> *Copy(
bool safe = false) const override {
return new LabelLookAheadMatcher<M, flags, Accumulator, Reachable>(*this,
safe);
}
MatchType Type(bool test) const override { return matcher_.Type(test); }
void SetState(StateId s) final {
if (state_ == s) return;
state_ = s;
match_set_state_ = false;
reach_set_state_ = false;
}
bool Find(Label label) final {
if (!match_set_state_) {
matcher_.SetState(state_);
match_set_state_ = true;
}
return matcher_.Find(label);
}
bool Done() const final { return matcher_.Done(); }
const Arc &Value() const final { return matcher_.Value(); }
void Next() final { matcher_.Next(); }
Weight Final(StateId s) const final { return matcher_.Final(s); }
ssize_t Priority(StateId s) final { return matcher_.Priority(s); }
const FST &GetFst() const override { return matcher_.GetFst(); }
uint64 Properties(uint64 inprops) const override {
auto outprops = matcher_.Properties(inprops);
if (error_ || (label_reachable_ && label_reachable_->Error())) {
outprops |= kError;
}
return outprops;
}
uint32 Flags() const override {
if (label_reachable_ && label_reachable_->GetData()->ReachInput()) {
return matcher_.Flags() | kFlags | kInputLookAheadMatcher;
} else if (label_reachable_ && !label_reachable_->GetData()->ReachInput()) {
return matcher_.Flags() | kFlags | kOutputLookAheadMatcher;
} else {
return matcher_.Flags();
}
}
const MatcherData *GetData() const {
return label_reachable_ ? label_reachable_->GetData() : nullptr;
};
std::shared_ptr<MatcherData> GetSharedData() const {
return label_reachable_ ? label_reachable_->GetSharedData()
: std::shared_ptr<MatcherData>();
}
// Checks if there is a matching (possibly super-final) transition at
// (state_, s).
template <class LFST>
bool LookAheadFst(const LFST &fst, StateId s);
// Required to make class concrete.
bool LookAheadFst(const Fst<Arc> &fst, StateId s) final {
return LookAheadFst<Fst<Arc>>(fst, s);
}
void InitLookAheadFst(const Fst<Arc> &fst, bool copy = false) override {
lfst_ = &fst;
if (label_reachable_) {
const bool reach_input = Type(false) == MATCH_OUTPUT;
label_reachable_->ReachInit(fst, reach_input, copy);
}
}
template <class LFST>
void InitLookAheadFst(const LFST &fst, bool copy = false) {
lfst_ = static_cast<const Fst<Arc> *>(&fst);
if (label_reachable_) {
const bool reach_input = Type(false) == MATCH_OUTPUT;
label_reachable_->ReachInit(fst, reach_input, copy);
}
}
bool LookAheadLabel(Label label) const final {
if (label == 0) return true;
if (label_reachable_) {
if (!reach_set_state_) {
label_reachable_->SetState(state_);
reach_set_state_ = true;
}
return label_reachable_->Reach(label);
} else {
return true;
}
}
private:
void Init(const FST &fst, MatchType match_type,
std::shared_ptr<MatcherData> data,
Accumulator *accumulator) {
if (!(kFlags & (kInputLookAheadMatcher | kOutputLookAheadMatcher))) {
FSTERROR() << "LabelLookaheadMatcher: Bad matcher flags: " << kFlags;
error_ = true;
}
const bool reach_input = match_type == MATCH_INPUT;
if (data) {
if (reach_input == data->ReachInput()) {
label_reachable_.reset(new Reachable(data, accumulator));
}
} else if ((reach_input && (kFlags & kInputLookAheadMatcher)) ||
(!reach_input && (kFlags & kOutputLookAheadMatcher))) {
label_reachable_.reset(new Reachable(fst, reach_input, accumulator,
kFlags & kLookAheadKeepRelabelData));
}
}
mutable M matcher_;
const Fst<Arc> *lfst_; // Look-ahead FST.
std::unique_ptr<Reachable> label_reachable_; // Label reachability info.
StateId state_; // Matcher state.
bool match_set_state_; // matcher_.SetState called?
mutable bool reach_set_state_; // reachable_.SetState called?
bool error_; // Error encountered?
};
template <class M, uint32 flags, class Accumulator, class Reachable>
template <class LFST>
inline bool LabelLookAheadMatcher<M, flags, Accumulator,
Reachable>::LookAheadFst(const LFST &fst,
StateId s) {
if (static_cast<const Fst<Arc> *>(&fst) != lfst_) InitLookAheadFst(fst);
ClearLookAheadWeight();
ClearLookAheadPrefix();
if (!label_reachable_) return true;
label_reachable_->SetState(state_, s);
reach_set_state_ = true;
bool compute_weight = kFlags & kLookAheadWeight;
bool compute_prefix = kFlags & kLookAheadPrefix;
ArcIterator<LFST> aiter(fst, s);
aiter.SetFlags(kArcNoCache, kArcNoCache); // Makes caching optional.
const bool reach_arc = label_reachable_->Reach(
&aiter, 0, internal::NumArcs(*lfst_, s), compute_weight);
const auto lfinal = internal::Final(*lfst_, s);
const bool reach_final =
lfinal != Weight::Zero() && label_reachable_->ReachFinal();
if (reach_arc) {
const auto begin = label_reachable_->ReachBegin();
const auto end = label_reachable_->ReachEnd();
if (compute_prefix && end - begin == 1 && !reach_final) {
aiter.Seek(begin);
SetLookAheadPrefix(aiter.Value());
compute_weight = false;
} else if (compute_weight) {
SetLookAheadWeight(label_reachable_->ReachWeight());
}
}
if (reach_final && compute_weight) {
SetLookAheadWeight(reach_arc ? Plus(LookAheadWeight(), lfinal) : lfinal);
}
return reach_arc || reach_final;
}
// Label-lookahead relabeling class.
template <class Arc, class Data = LabelReachableData<typename Arc::Label>>
class LabelLookAheadRelabeler {
public:
using Label = typename Arc::Label;
using Reachable = LabelReachable<Arc, DefaultAccumulator<Arc>, Data>;
// Relabels matcher FST (initialization function object).
template <typename Impl>
explicit LabelLookAheadRelabeler(std::shared_ptr<Impl> *impl);
// Relabels arbitrary FST. Class LFST should be a label-lookahead FST.
template <class LFST>
static void Relabel(MutableFst<Arc> *fst, const LFST &mfst,
bool relabel_input) {
const auto *data = mfst.GetAddOn();
Reachable reachable(data->First() ? data->SharedFirst()
: data->SharedSecond());
reachable.Relabel(fst, relabel_input);
}
// Returns relabeling pairs (cf. relabel.h::Relabel()). Class LFST should be a
// label-lookahead FST. If avoid_collisions is true, extra pairs are added to
// ensure no collisions when relabeling automata that have labels unseen here.
template <class LFST>
static void RelabelPairs(const LFST &mfst,
std::vector<std::pair<Label, Label>> *pairs,
bool avoid_collisions = false) {
const auto *data = mfst.GetAddOn();
Reachable reachable(data->First() ? data->SharedFirst()
: data->SharedSecond());
reachable.RelabelPairs(pairs, avoid_collisions);
}
};
template <class Arc, class Data>
template <typename Impl>
inline LabelLookAheadRelabeler<Arc, Data>::LabelLookAheadRelabeler(
std::shared_ptr<Impl> *impl) {
Fst<Arc> &fst = (*impl)->GetFst();
auto data = (*impl)->GetSharedAddOn();
const auto name = (*impl)->Type();
const bool is_mutable = fst.Properties(kMutable, false);
std::unique_ptr<MutableFst<Arc>> mfst;
if (is_mutable) {
mfst.reset(static_cast<MutableFst<Arc> *>(&fst));
} else {
mfst.reset(new VectorFst<Arc>(fst));
}
if (data->First()) { // reach_input.
Reachable reachable(data->SharedFirst());
reachable.Relabel(mfst.get(), true);
if (!FLAGS_save_relabel_ipairs.empty()) {
std::vector<std::pair<Label, Label>> pairs;
reachable.RelabelPairs(&pairs, true);
WriteLabelPairs(FLAGS_save_relabel_ipairs, pairs);
}
} else {
Reachable reachable(data->SharedSecond());
reachable.Relabel(mfst.get(), false);
if (!FLAGS_save_relabel_opairs.empty()) {
std::vector<std::pair<Label, Label>> pairs;
reachable.RelabelPairs(&pairs, true);
WriteLabelPairs(FLAGS_save_relabel_opairs, pairs);
}
}
if (!is_mutable) {
*impl = std::make_shared<Impl>(*mfst, name);
(*impl)->SetAddOn(data);
}
}
// Generic lookahead matcher, templated on the FST definition (a wrapper around
// a pointer to specific one).
template <class F>
class LookAheadMatcher {
public:
using FST = F;
using Arc = typename FST::Arc;
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
using LBase = LookAheadMatcherBase<Arc>;
// This makes a copy of the FST.
LookAheadMatcher(const FST &fst, MatchType match_type)
: owned_fst_(fst.Copy()),
base_(owned_fst_->InitMatcher(match_type)),
lookahead_(false) {
if (!base_) base_.reset(new SortedMatcher<FST>(owned_fst_.get(),
match_type));
}
// This doesn't copy the FST.
LookAheadMatcher(const FST *fst, MatchType match_type)
: base_(fst->InitMatcher(match_type)),
lookahead_(false) {
if (!base_) base_.reset(new SortedMatcher<FST>(fst, match_type));
}
// This makes a copy of the FST.
LookAheadMatcher(const LookAheadMatcher<FST> &matcher, bool safe = false)
: base_(matcher.base_->Copy(safe)),
lookahead_(matcher.lookahead_) { }
// Takes ownership of base.
explicit LookAheadMatcher(MatcherBase<Arc> *base)
: base_(base), lookahead_(false) {}
LookAheadMatcher<FST> *Copy(bool safe = false) const {
return new LookAheadMatcher<FST>(*this, safe);
}
MatchType Type(bool test) const { return base_->Type(test); }
void SetState(StateId s) { base_->SetState(s); }
bool Find(Label label) { return base_->Find(label); }
bool Done() const { return base_->Done(); }
const Arc &Value() const { return base_->Value(); }
void Next() { base_->Next(); }
Weight Final(StateId s) const { return base_->Final(s); }
ssize_t Priority(StateId s) { return base_->Priority(s); }
const FST &GetFst() const {
return static_cast<const FST &>(base_->GetFst());
}
uint64 Properties(uint64 props) const { return base_->Properties(props); }
uint32 Flags() const { return base_->Flags(); }
bool LookAheadLabel(Label label) const {
if (LookAheadCheck()) {
return static_cast<LBase *>(base_.get())->LookAheadLabel(label);
} else {
return true;
}
}
bool LookAheadFst(const Fst<Arc> &fst, StateId s) {
if (LookAheadCheck()) {
return static_cast<LBase *>(base_.get())->LookAheadFst(fst, s);
} else {
return true;
}
}
Weight LookAheadWeight() const {
if (LookAheadCheck()) {
return static_cast<LBase *>(base_.get())->LookAheadWeight();
} else {
return Weight::One();
}
}
bool LookAheadPrefix(Arc *arc) const {
if (LookAheadCheck()) {
return static_cast<LBase *>(base_.get())->LookAheadPrefix(arc);
} else {
return false;
}
}
void InitLookAheadFst(const Fst<Arc> &fst, bool copy = false) {
if (LookAheadCheck()) {
static_cast<LBase *>(base_.get())->InitLookAheadFst(fst, copy);
}
}
private:
bool LookAheadCheck() const {
if (!lookahead_) {
lookahead_ =
base_->Flags() & (kInputLookAheadMatcher | kOutputLookAheadMatcher);
if (!lookahead_) {
FSTERROR() << "LookAheadMatcher: No look-ahead matcher defined";
}
}
return lookahead_;
}
std::unique_ptr<const FST> owned_fst_;
std::unique_ptr<MatcherBase<Arc>> base_;
mutable bool lookahead_;
LookAheadMatcher &operator=(const LookAheadMatcher &) = delete;
};
} // namespace fst
#endif // FST_LOOKAHEAD_MATCHER_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions/far/far.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Finite-State Transducer (FST) archive classes.
#ifndef FST_EXTENSIONS_FAR_FAR_H_
#define FST_EXTENSIONS_FAR_FAR_H_
#include <iostream>
#include <sstream>
#include <fst/log.h>
#include <fst/extensions/far/stlist.h>
#include <fst/extensions/far/sttable.h>
#include <fst/fst.h>
#include <fst/vector-fst.h>
#include <fstream>
namespace fst {
enum FarEntryType { FET_LINE, FET_FILE };
enum FarTokenType { FTT_SYMBOL, FTT_BYTE, FTT_UTF8 };
inline bool IsFst(const string &filename) {
std::ifstream strm(filename, std::ios_base::in | std::ios_base::binary);
if (!strm) return false;
return IsFstHeader(strm, filename);
}
// FST archive header class
class FarHeader {
public:
const string &ArcType() const { return arctype_; }
const string &FarType() const { return fartype_; }
bool Read(const string &filename) {
FstHeader fsthdr;
if (filename.empty()) {
// Header reading unsupported on stdin. Assumes STList and StdArc.
fartype_ = "stlist";
arctype_ = "standard";
return true;
} else if (IsSTTable(filename)) { // Checks if STTable.
ReadSTTableHeader(filename, &fsthdr);
fartype_ = "sttable";
arctype_ = fsthdr.ArcType().empty() ? "unknown" : fsthdr.ArcType();
return true;
} else if (IsSTList(filename)) { // Checks if STList.
ReadSTListHeader(filename, &fsthdr);
fartype_ = "stlist";
arctype_ = fsthdr.ArcType().empty() ? "unknown" : fsthdr.ArcType();
return true;
} else if (IsFst(filename)) { // Checks if FST.
std::ifstream istrm(filename,
std::ios_base::in | std::ios_base::binary);
fsthdr.Read(istrm, filename);
fartype_ = "fst";
arctype_ = fsthdr.ArcType().empty() ? "unknown" : fsthdr.ArcType();
return true;
}
return false;
}
private:
string fartype_;
string arctype_;
};
enum FarType {
FAR_DEFAULT = 0,
FAR_STTABLE = 1,
FAR_STLIST = 2,
FAR_FST = 3,
};
// This class creates an archive of FSTs.
template <class A>
class FarWriter {
public:
using Arc = A;
// Creates a new (empty) FST archive; returns null on error.
static FarWriter *Create(const string &filename, FarType type = FAR_DEFAULT);
// Adds an FST to the end of an archive. Keys must be non-empty and
// in lexicographic order. FSTs must have a suitable write method.
virtual void Add(const string &key, const Fst<Arc> &fst) = 0;
virtual FarType Type() const = 0;
virtual bool Error() const = 0;
virtual ~FarWriter() {}
protected:
FarWriter() {}
};
// This class iterates through an existing archive of FSTs.
template <class A>
class FarReader {
public:
using Arc = A;
// Opens an existing FST archive in a single file; returns null on error.
// Sets current position to the beginning of the achive.
static FarReader *Open(const string &filename);
// Opens an existing FST archive in multiple files; returns null on error.
// Sets current position to the beginning of the achive.
static FarReader *Open(const std::vector<string> &filenames);
// Resets current position to beginning of archive.
virtual void Reset() = 0;
// Sets current position to first entry >= key. Returns true if a match.
virtual bool Find(const string &key) = 0;
// Current position at end of archive?
virtual bool Done() const = 0;
// Move current position to next FST.
virtual void Next() = 0;
// Returns key at the current position. This reference is invalidated if
// the current position in the archive is changed.
virtual const string &GetKey() const = 0;
// Returns pointer to FST at the current position. This is invalidated if
// the current position in the archive is changed.
virtual const Fst<Arc> *GetFst() const = 0;
virtual FarType Type() const = 0;
virtual bool Error() const = 0;
virtual ~FarReader() {}
protected:
FarReader() {}
};
template <class Arc>
class FstWriter {
public:
void operator()(std::ostream &strm, const Fst<Arc> &fst) const {
fst.Write(strm, FstWriteOptions());
}
};
template <class A>
class STTableFarWriter : public FarWriter<A> {
public:
using Arc = A;
static STTableFarWriter *Create(const string &filename) {
auto *writer = STTableWriter<Fst<Arc>, FstWriter<Arc>>::Create(filename);
return new STTableFarWriter(writer);
}
void Add(const string &key, const Fst<Arc> &fst) final {
writer_->Add(key, fst);
}
FarType Type() const final { return FAR_STTABLE; }
bool Error() const final { return writer_->Error(); }
private:
explicit STTableFarWriter(STTableWriter<Fst<Arc>, FstWriter<Arc>> *writer)
: writer_(writer) {}
std::unique_ptr<STTableWriter<Fst<Arc>, FstWriter<Arc>>> writer_;
};
template <class A>
class STListFarWriter : public FarWriter<A> {
public:
using Arc = A;
static STListFarWriter *Create(const string &filename) {
auto *writer = STListWriter<Fst<Arc>, FstWriter<Arc>>::Create(filename);
return new STListFarWriter(writer);
}
void Add(const string &key, const Fst<Arc> &fst) final {
writer_->Add(key, fst);
}
constexpr FarType Type() const final { return FAR_STLIST; }
bool Error() const final { return writer_->Error(); }
private:
explicit STListFarWriter(STListWriter<Fst<Arc>, FstWriter<Arc>> *writer)
: writer_(writer) {}
std::unique_ptr<STListWriter<Fst<Arc>, FstWriter<Arc>>> writer_;
};
template <class A>
class FstFarWriter : public FarWriter<A> {
public:
using Arc = A;
explicit FstFarWriter(const string &filename)
: filename_(filename), error_(false), written_(false) {}
static FstFarWriter *Create(const string &filename) {
return new FstFarWriter(filename);
}
void Add(const string &key, const Fst<A> &fst) final {
if (written_) {
LOG(WARNING) << "FstFarWriter::Add: only one FST supported,"
<< " subsequent entries discarded.";
} else {
error_ = !fst.Write(filename_);
written_ = true;
}
}
constexpr FarType Type() const final { return FAR_FST; }
bool Error() const final { return error_; }
~FstFarWriter() final {}
private:
string filename_;
bool error_;
bool written_;
};
template <class Arc>
FarWriter<Arc> *FarWriter<Arc>::Create(const string &filename, FarType type) {
switch (type) {
case FAR_DEFAULT:
if (filename.empty()) return STListFarWriter<Arc>::Create(filename);
case FAR_STTABLE:
return STTableFarWriter<Arc>::Create(filename);
case FAR_STLIST:
return STListFarWriter<Arc>::Create(filename);
case FAR_FST:
return FstFarWriter<Arc>::Create(filename);
default:
LOG(ERROR) << "FarWriter::Create: Unknown FAR type";
return nullptr;
}
}
template <class Arc>
class FstReader {
public:
Fst<Arc> *operator()(std::istream &strm) const {
return Fst<Arc>::Read(strm, FstReadOptions());
}
};
template <class A>
class STTableFarReader : public FarReader<A> {
public:
using Arc = A;
static STTableFarReader *Open(const string &filename) {
auto *reader = STTableReader<Fst<Arc>, FstReader<Arc>>::Open(filename);
if (!reader || reader->Error()) return nullptr;
return new STTableFarReader(reader);
}
static STTableFarReader *Open(const std::vector<string> &filenames) {
auto *reader = STTableReader<Fst<Arc>, FstReader<Arc>>::Open(filenames);
if (!reader || reader->Error()) return nullptr;
return new STTableFarReader(reader);
}
void Reset() final { reader_->Reset(); }
bool Find(const string &key) final { return reader_->Find(key); }
bool Done() const final { return reader_->Done(); }
void Next() final { return reader_->Next(); }
const string &GetKey() const final { return reader_->GetKey(); }
const Fst<Arc> *GetFst() const final { return reader_->GetEntry(); }
constexpr FarType Type() const final { return FAR_STTABLE; }
bool Error() const final { return reader_->Error(); }
private:
explicit STTableFarReader(STTableReader<Fst<Arc>, FstReader<Arc>> *reader)
: reader_(reader) {}
std::unique_ptr<STTableReader<Fst<Arc>, FstReader<Arc>>> reader_;
};
template <class A>
class STListFarReader : public FarReader<A> {
public:
using Arc = A;
static STListFarReader *Open(const string &filename) {
auto *reader = STListReader<Fst<Arc>, FstReader<Arc>>::Open(filename);
if (!reader || reader->Error()) return nullptr;
return new STListFarReader(reader);
}
static STListFarReader *Open(const std::vector<string> &filenames) {
auto *reader = STListReader<Fst<Arc>, FstReader<Arc>>::Open(filenames);
if (!reader || reader->Error()) return nullptr;
return new STListFarReader(reader);
}
void Reset() final { reader_->Reset(); }
bool Find(const string &key) final { return reader_->Find(key); }
bool Done() const final { return reader_->Done(); }
void Next() final { return reader_->Next(); }
const string &GetKey() const final { return reader_->GetKey(); }
const Fst<Arc> *GetFst() const final { return reader_->GetEntry(); }
constexpr FarType Type() const final { return FAR_STLIST; }
bool Error() const final { return reader_->Error(); }
private:
explicit STListFarReader(STListReader<Fst<Arc>, FstReader<Arc>> *reader)
: reader_(reader) {}
std::unique_ptr<STListReader<Fst<Arc>, FstReader<Arc>>> reader_;
};
template <class A>
class FstFarReader : public FarReader<A> {
public:
using Arc = A;
static FstFarReader *Open(const string &filename) {
std::vector<string> filenames;
filenames.push_back(filename);
return new FstFarReader<Arc>(filenames);
}
static FstFarReader *Open(const std::vector<string> &filenames) {
return new FstFarReader<Arc>(filenames);
}
explicit FstFarReader(const std::vector<string> &filenames)
: keys_(filenames), has_stdin_(false), pos_(0), error_(false) {
std::sort(keys_.begin(), keys_.end());
streams_.resize(keys_.size(), 0);
for (size_t i = 0; i < keys_.size(); ++i) {
if (keys_[i].empty()) {
if (!has_stdin_) {
streams_[i] = &std::cin;
// sources_[i] = "stdin";
has_stdin_ = true;
} else {
FSTERROR() << "FstFarReader::FstFarReader: standard input should "
"only appear once in the input file list";
error_ = true;
return;
}
} else {
streams_[i] = new std::ifstream(
keys_[i], std::ios_base::in | std::ios_base::binary);
}
}
if (pos_ >= keys_.size()) return;
ReadFst();
}
void Reset() final {
if (has_stdin_) {
FSTERROR()
<< "FstFarReader::Reset: Operation not supported on standard input";
error_ = true;
return;
}
pos_ = 0;
ReadFst();
}
bool Find(const string &key) final {
if (has_stdin_) {
FSTERROR()
<< "FstFarReader::Find: Operation not supported on standard input";
error_ = true;
return false;
}
pos_ = 0; // TODO
ReadFst();
return true;
}
bool Done() const final { return error_ || pos_ >= keys_.size(); }
void Next() final {
++pos_;
ReadFst();
}
const string &GetKey() const final { return keys_[pos_]; }
const Fst<Arc> *GetFst() const final { return fst_.get(); }
constexpr FarType Type() const final { return FAR_FST; }
bool Error() const final { return error_; }
~FstFarReader() final {
for (size_t i = 0; i < keys_.size(); ++i) {
if (streams_[i] != &std::cin) {
delete streams_[i];
}
}
}
private:
void ReadFst() {
fst_.reset();
if (pos_ >= keys_.size()) return;
streams_[pos_]->seekg(0);
fst_.reset(Fst<Arc>::Read(*streams_[pos_], FstReadOptions()));
if (!fst_) {
FSTERROR() << "FstFarReader: Error reading Fst from: " << keys_[pos_];
error_ = true;
}
}
std::vector<string> keys_;
std::vector<std::istream *> streams_;
bool has_stdin_;
size_t pos_;
mutable std::unique_ptr<Fst<Arc>> fst_;
mutable bool error_;
};
template <class Arc>
FarReader<Arc> *FarReader<Arc>::Open(const string &filename) {
if (filename.empty())
return STListFarReader<Arc>::Open(filename);
else if (IsSTTable(filename))
return STTableFarReader<Arc>::Open(filename);
else if (IsSTList(filename))
return STListFarReader<Arc>::Open(filename);
else if (IsFst(filename))
return FstFarReader<Arc>::Open(filename);
return nullptr;
}
template <class Arc>
FarReader<Arc> *FarReader<Arc>::Open(const std::vector<string> &filenames) {
if (!filenames.empty() && filenames[0].empty())
return STListFarReader<Arc>::Open(filenames);
else if (!filenames.empty() && IsSTTable(filenames[0]))
return STTableFarReader<Arc>::Open(filenames);
else if (!filenames.empty() && IsSTList(filenames[0]))
return STListFarReader<Arc>::Open(filenames);
else if (!filenames.empty() && IsFst(filenames[0]))
return FstFarReader<Arc>::Open(filenames);
return nullptr;
}
} // namespace fst
#endif // FST_EXTENSIONS_FAR_FAR_H_
| 0 |
coqui_public_repos/STT/native_client/dotnet/STTClient | coqui_public_repos/STT/native_client/dotnet/STTClient/Structs/CandidateTranscript.cs | using System;
using System.Runtime.InteropServices;
namespace STTClient.Structs
{
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CandidateTranscript
{
/// <summary>
/// Native list of tokens.
/// </summary>
internal unsafe IntPtr tokens;
/// <summary>
/// Count of tokens from the native side.
/// </summary>
internal unsafe int num_tokens;
/// <summary>
/// Approximated confidence value for this transcription.
/// </summary>
internal unsafe double confidence;
}
}
| 0 |
coqui_public_repos/inference-engine/third_party/kenlm | coqui_public_repos/inference-engine/third_party/kenlm/util/file_stream.hh | /* Like std::ofstream but without being incredibly slow. Backed by a raw fd.
* Supports most of the built-in types except for long double.
*/
#ifndef UTIL_FILE_STREAM_H
#define UTIL_FILE_STREAM_H
#include "util/fake_ostream.hh"
#include "util/file.hh"
#include "util/scoped.hh"
#include <cassert>
#include <cstring>
#include <stdint.h>
namespace util {
class FileStream : public FakeOStream<FileStream> {
public:
explicit FileStream(int out = -1, std::size_t buffer_size = 8192)
: buf_(util::MallocOrThrow(std::max<std::size_t>(buffer_size, kToStringMaxBytes))),
current_(static_cast<char*>(buf_.get())),
end_(current_ + std::max<std::size_t>(buffer_size, kToStringMaxBytes)),
fd_(out) {}
#if __cplusplus >= 201103L
FileStream(FileStream &&from) noexcept : buf_(from.buf_.release()), current_(from.current_), end_(from.end_), fd_(from.fd_) {
from.end_ = reinterpret_cast<char*>(from.buf_.get());
from.current_ = from.end_;
}
#endif
~FileStream() {
flush();
}
void SetFD(int to) {
flush();
fd_ = to;
}
FileStream &flush() {
if (current_ != buf_.get()) {
util::WriteOrThrow(fd_, buf_.get(), current_ - (char*)buf_.get());
current_ = static_cast<char*>(buf_.get());
}
return *this;
}
// For writes of arbitrary size.
FileStream &write(const void *data, std::size_t length) {
if (UTIL_LIKELY(current_ + length <= end_)) {
std::memcpy(current_, data, length);
current_ += length;
return *this;
}
flush();
if (current_ + length <= end_) {
std::memcpy(current_, data, length);
current_ += length;
} else {
util::WriteOrThrow(fd_, data, length);
}
return *this;
}
FileStream &seekp(uint64_t to) {
flush();
util::SeekOrThrow(fd_, to);
return *this;
}
protected:
friend class FakeOStream<FileStream>;
// For writes directly to buffer guaranteed to have amount < buffer size.
char *Ensure(std::size_t amount) {
if (UTIL_UNLIKELY(current_ + amount > end_)) {
flush();
assert(current_ + amount <= end_);
}
return current_;
}
void AdvanceTo(char *to) {
current_ = to;
assert(current_ <= end_);
}
private:
util::scoped_malloc buf_;
char *current_, *end_;
int fd_;
};
} // namespace
#endif
| 0 |
coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/providers | coqui_public_repos/inference-engine/third_party/onnxruntime/include/onnxruntime/core/providers/cuda/cuda_provider_factory.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "onnxruntime_c_api.h"
#ifdef __cplusplus
#include "core/framework/provider_options.h"
namespace onnxruntime {
class IAllocator;
class IDataTransfer;
struct IExecutionProviderFactory;
struct CUDAExecutionProviderInfo;
enum class ArenaExtendStrategy : int32_t;
struct CUDAExecutionProviderExternalAllocatorInfo;
namespace cuda {
class INcclService;
}
} // namespace onnxruntime
struct ProviderInfo_CUDA {
virtual OrtStatus* SetCurrentGpuDeviceId(_In_ int device_id) = 0;
virtual OrtStatus* GetCurrentGpuDeviceId(_In_ int* device_id) = 0;
virtual std::unique_ptr<onnxruntime::IAllocator> CreateCUDAAllocator(int16_t device_id, const char* name) = 0;
virtual std::unique_ptr<onnxruntime::IAllocator> CreateCUDAPinnedAllocator(int16_t device_id, const char* name) = 0;
virtual std::unique_ptr<onnxruntime::IDataTransfer> CreateGPUDataTransfer(void* stream) = 0;
virtual void cuda__Impl_Cast(void* stream, const int64_t* input_data, int32_t* output_data, size_t count) = 0;
virtual void cuda__Impl_Cast(void* stream, const int32_t* input_data, int64_t* output_data, size_t count) = 0;
virtual bool CudaCall_false(int retCode, const char* exprString, const char* libName, int successCode, const char* msg) = 0;
virtual bool CudaCall_true(int retCode, const char* exprString, const char* libName, int successCode, const char* msg) = 0;
virtual void CopyGpuToCpu(void* dst_ptr, const void* src_ptr, const size_t size, const OrtMemoryInfo& dst_location, const OrtMemoryInfo& src_location) = 0;
virtual void cudaMemcpy_HostToDevice(void* dst, const void* src, size_t count) = 0;
virtual void cudaMemcpy_DeviceToHost(void* dst, const void* src, size_t count) = 0;
virtual int cudaGetDeviceCount() = 0;
virtual void CUDAExecutionProviderInfo__FromProviderOptions(const onnxruntime::ProviderOptions& options, onnxruntime::CUDAExecutionProviderInfo& info) = 0;
#if defined(USE_CUDA) && defined(ORT_USE_NCCL) && defined(USE_NCCL_P2P)
virtual onnxruntime::cuda::INcclService& GetINcclService() = 0;
#endif
virtual std::shared_ptr<onnxruntime::IExecutionProviderFactory> CreateExecutionProviderFactory(const onnxruntime::CUDAExecutionProviderInfo& info) = 0;
virtual std::shared_ptr<onnxruntime::IAllocator> CreateCudaAllocator(int16_t device_id, size_t gpu_mem_limit, onnxruntime::ArenaExtendStrategy arena_extend_strategy, onnxruntime::CUDAExecutionProviderExternalAllocatorInfo& external_allocator_info, OrtArenaCfg* default_memory_arena_cfg) = 0;
};
extern "C" {
#endif
/**
* \param device_id cuda device id, starts from zero.
*/
ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id);
#ifdef __cplusplus
}
#endif
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions/special/phi-fst.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_EXTENSIONS_SPECIAL_PHI_FST_H_
#define FST_EXTENSIONS_SPECIAL_PHI_FST_H_
#include <memory>
#include <string>
#include <fst/const-fst.h>
#include <fst/matcher-fst.h>
#include <fst/matcher.h>
DECLARE_int64_t(phi_fst_phi_label);
DECLARE_bool(phi_fst_phi_loop);
DECLARE_string(phi_fst_rewrite_mode);
namespace fst {
namespace internal {
template <class Label>
class PhiFstMatcherData {
public:
PhiFstMatcherData(
Label phi_label = FLAGS_phi_fst_phi_label,
bool phi_loop = FLAGS_phi_fst_phi_loop,
MatcherRewriteMode rewrite_mode = RewriteMode(FLAGS_phi_fst_rewrite_mode))
: phi_label_(phi_label),
phi_loop_(phi_loop),
rewrite_mode_(rewrite_mode) {}
PhiFstMatcherData(const PhiFstMatcherData &data)
: phi_label_(data.phi_label_),
phi_loop_(data.phi_loop_),
rewrite_mode_(data.rewrite_mode_) {}
static PhiFstMatcherData<Label> *Read(std::istream &istrm,
const FstReadOptions &read) {
auto *data = new PhiFstMatcherData<Label>();
ReadType(istrm, &data->phi_label_);
ReadType(istrm, &data->phi_loop_);
int32_t rewrite_mode;
ReadType(istrm, &rewrite_mode);
data->rewrite_mode_ = static_cast<MatcherRewriteMode>(rewrite_mode);
return data;
}
bool Write(std::ostream &ostrm, const FstWriteOptions &opts) const {
WriteType(ostrm, phi_label_);
WriteType(ostrm, phi_loop_);
WriteType(ostrm, static_cast<int32_t>(rewrite_mode_));
return !ostrm ? false : true;
}
Label PhiLabel() const { return phi_label_; }
bool PhiLoop() const { return phi_loop_; }
MatcherRewriteMode RewriteMode() const { return rewrite_mode_; }
private:
static MatcherRewriteMode RewriteMode(const string &mode) {
if (mode == "auto") return MATCHER_REWRITE_AUTO;
if (mode == "always") return MATCHER_REWRITE_ALWAYS;
if (mode == "never") return MATCHER_REWRITE_NEVER;
LOG(WARNING) << "PhiFst: Unknown rewrite mode: " << mode << ". "
<< "Defaulting to auto.";
return MATCHER_REWRITE_AUTO;
}
Label phi_label_;
bool phi_loop_;
MatcherRewriteMode rewrite_mode_;
};
} // namespace internal
constexpr uint8_t kPhiFstMatchInput = 0x01; // Input matcher is PhiMatcher.
constexpr uint8_t kPhiFstMatchOutput = 0x02; // Output matcher is PhiMatcher.
template <class M, uint8_t flags = kPhiFstMatchInput | kPhiFstMatchOutput>
class PhiFstMatcher : public PhiMatcher<M> {
public:
using FST = typename M::FST;
using Arc = typename M::Arc;
using StateId = typename Arc::StateId;
using Label = typename Arc::Label;
using Weight = typename Arc::Weight;
using MatcherData = internal::PhiFstMatcherData<Label>;
enum : uint8_t { kFlags = flags };
// This makes a copy of the FST.
PhiFstMatcher(const FST &fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::make_shared<MatcherData>())
: PhiMatcher<M>(fst, match_type,
PhiLabel(match_type, data ? data->PhiLabel()
: MatcherData().PhiLabel()),
data ? data->PhiLoop() : MatcherData().PhiLoop(),
data ? data->RewriteMode() : MatcherData().RewriteMode()),
data_(data) {}
// This doesn't copy the FST.
PhiFstMatcher(const FST *fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::make_shared<MatcherData>())
: PhiMatcher<M>(fst, match_type,
PhiLabel(match_type, data ? data->PhiLabel()
: MatcherData().PhiLabel()),
data ? data->PhiLoop() : MatcherData().PhiLoop(),
data ? data->RewriteMode() : MatcherData().RewriteMode()),
data_(data) {}
// This makes a copy of the FST.
PhiFstMatcher(const PhiFstMatcher<M, flags> &matcher, bool safe = false)
: PhiMatcher<M>(matcher, safe), data_(matcher.data_) {}
PhiFstMatcher<M, flags> *Copy(bool safe = false) const override {
return new PhiFstMatcher<M, flags>(*this, safe);
}
const MatcherData *GetData() const { return data_.get(); }
std::shared_ptr<MatcherData> GetSharedData() const { return data_; }
private:
static Label PhiLabel(MatchType match_type, Label label) {
if (match_type == MATCH_INPUT && flags & kPhiFstMatchInput) return label;
if (match_type == MATCH_OUTPUT && flags & kPhiFstMatchOutput) return label;
return kNoLabel;
}
std::shared_ptr<MatcherData> data_;
};
extern const char phi_fst_type[];
extern const char input_phi_fst_type[];
extern const char output_phi_fst_type[];
using StdPhiFst =
MatcherFst<ConstFst<StdArc>, PhiFstMatcher<SortedMatcher<ConstFst<StdArc>>>,
phi_fst_type>;
using LogPhiFst =
MatcherFst<ConstFst<LogArc>, PhiFstMatcher<SortedMatcher<ConstFst<LogArc>>>,
phi_fst_type>;
using Log64PhiFst = MatcherFst<ConstFst<Log64Arc>,
PhiFstMatcher<SortedMatcher<ConstFst<Log64Arc>>>,
input_phi_fst_type>;
using StdInputPhiFst =
MatcherFst<ConstFst<StdArc>, PhiFstMatcher<SortedMatcher<ConstFst<StdArc>>,
kPhiFstMatchInput>,
input_phi_fst_type>;
using LogInputPhiFst =
MatcherFst<ConstFst<LogArc>, PhiFstMatcher<SortedMatcher<ConstFst<LogArc>>,
kPhiFstMatchInput>,
input_phi_fst_type>;
using Log64InputPhiFst = MatcherFst<
ConstFst<Log64Arc>,
PhiFstMatcher<SortedMatcher<ConstFst<Log64Arc>>, kPhiFstMatchInput>,
input_phi_fst_type>;
using StdOutputPhiFst =
MatcherFst<ConstFst<StdArc>, PhiFstMatcher<SortedMatcher<ConstFst<StdArc>>,
kPhiFstMatchOutput>,
output_phi_fst_type>;
using LogOutputPhiFst =
MatcherFst<ConstFst<LogArc>, PhiFstMatcher<SortedMatcher<ConstFst<LogArc>>,
kPhiFstMatchOutput>,
output_phi_fst_type>;
using Log64OutputPhiFst = MatcherFst<
ConstFst<Log64Arc>,
PhiFstMatcher<SortedMatcher<ConstFst<Log64Arc>>, kPhiFstMatchOutput>,
output_phi_fst_type>;
} // namespace fst
#endif // FST_EXTENSIONS_SPECIAL_PHI_FST_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/extensions/far/far-class.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/extensions/far/far-class.h>
#include <fst/script/script-impl.h>
#include <fst/extensions/far/script-impl.h>
namespace fst {
namespace script {
// FarReaderClass.
FarReaderClass *FarReaderClass::Open(const string &filename) {
OpenFarReaderClassArgs1 args(filename);
args.retval = nullptr;
Apply<Operation<OpenFarReaderClassArgs1>>("OpenFarReaderClass",
LoadArcTypeFromFar(filename),
&args);
return args.retval;
}
FarReaderClass *FarReaderClass::Open(const std::vector<string> &filenames) {
if (filenames.empty()) {
LOG(ERROR) << "FarReaderClass::Open: No files specified";
return nullptr;
}
const auto arc_type = LoadArcTypeFromFar(filenames.front());
if (arc_type.empty()) return nullptr;
OpenFarReaderClassArgs2 args(filenames);
args.retval = nullptr;
Apply<Operation<OpenFarReaderClassArgs2>>("OpenFarReaderClass", arc_type,
&args);
return args.retval;
}
REGISTER_FST_OPERATION(OpenFarReaderClass, StdArc, OpenFarReaderClassArgs1);
REGISTER_FST_OPERATION(OpenFarReaderClass, LogArc, OpenFarReaderClassArgs1);
REGISTER_FST_OPERATION(OpenFarReaderClass, Log64Arc, OpenFarReaderClassArgs1);
REGISTER_FST_OPERATION(OpenFarReaderClass, StdArc, OpenFarReaderClassArgs2);
REGISTER_FST_OPERATION(OpenFarReaderClass, LogArc, OpenFarReaderClassArgs2);
REGISTER_FST_OPERATION(OpenFarReaderClass, Log64Arc, OpenFarReaderClassArgs2);
// FarWriterClass.
FarWriterClass *FarWriterClass::Create(const string &filename,
const string &arc_type, FarType type) {
CreateFarWriterClassInnerArgs iargs(filename, type);
CreateFarWriterClassArgs args(iargs);
args.retval = nullptr;
Apply<Operation<CreateFarWriterClassArgs>>("CreateFarWriterClass", arc_type,
&args);
return args.retval;
}
REGISTER_FST_OPERATION(CreateFarWriterClass, StdArc, CreateFarWriterClassArgs);
REGISTER_FST_OPERATION(CreateFarWriterClass, LogArc, CreateFarWriterClassArgs);
REGISTER_FST_OPERATION(CreateFarWriterClass, Log64Arc,
CreateFarWriterClassArgs);
} // namespace script
} // namespace fst
| 0 |
coqui_public_repos/TTS/recipes/thorsten_DE | coqui_public_repos/TTS/recipes/thorsten_DE/wavegrad/train_wavegrad.py | import os
from trainer import Trainer, TrainerArgs
from TTS.utils.audio import AudioProcessor
from TTS.utils.downloaders import download_thorsten_de
from TTS.vocoder.configs import WavegradConfig
from TTS.vocoder.datasets.preprocess import load_wav_data
from TTS.vocoder.models.wavegrad import Wavegrad
output_path = os.path.dirname(os.path.abspath(__file__))
config = WavegradConfig(
batch_size=32,
eval_batch_size=16,
num_loader_workers=4,
num_eval_loader_workers=4,
run_eval=True,
test_delay_epochs=-1,
epochs=1000,
seq_len=6144,
pad_short=2000,
use_noise_augment=True,
eval_split_size=50,
print_step=50,
print_eval=True,
mixed_precision=False,
data_path=os.path.join(output_path, "../thorsten-de/wavs/"),
output_path=output_path,
)
# download dataset if not already present
if not os.path.exists(config.data_path):
print("Downloading dataset")
download_path = os.path.abspath(os.path.join(os.path.abspath(config.data_path), "../../"))
download_thorsten_de(download_path)
# init audio processor
ap = AudioProcessor(**config.audio.to_dict())
# load training samples
eval_samples, train_samples = load_wav_data(config.data_path, config.eval_split_size)
# init model
model = Wavegrad(config)
# init the trainer and 🚀
trainer = Trainer(
TrainerArgs(),
config,
output_path,
model=model,
train_samples=train_samples,
eval_samples=eval_samples,
training_assets={"audio_processor": ap},
)
trainer.fit()
| 0 |
coqui_public_repos/TTS/TTS/tts | coqui_public_repos/TTS/TTS/tts/datasets/dataset.py | import base64
import collections
import os
import random
from typing import Dict, List, Union
import numpy as np
import torch
import tqdm
from torch.utils.data import Dataset
from TTS.tts.utils.data import prepare_data, prepare_stop_target, prepare_tensor
from TTS.utils.audio import AudioProcessor
from TTS.utils.audio.numpy_transforms import compute_energy as calculate_energy
# to prevent too many open files error as suggested here
# https://github.com/pytorch/pytorch/issues/11201#issuecomment-421146936
torch.multiprocessing.set_sharing_strategy("file_system")
def _parse_sample(item):
language_name = None
attn_file = None
if len(item) == 5:
text, wav_file, speaker_name, language_name, attn_file = item
elif len(item) == 4:
text, wav_file, speaker_name, language_name = item
elif len(item) == 3:
text, wav_file, speaker_name = item
else:
raise ValueError(" [!] Dataset cannot parse the sample.")
return text, wav_file, speaker_name, language_name, attn_file
def noise_augment_audio(wav):
return wav + (1.0 / 32768.0) * np.random.rand(*wav.shape)
def string2filename(string):
# generate a safe and reversible filename based on a string
filename = base64.urlsafe_b64encode(string.encode("utf-8")).decode("utf-8", "ignore")
return filename
class TTSDataset(Dataset):
def __init__(
self,
outputs_per_step: int = 1,
compute_linear_spec: bool = False,
ap: AudioProcessor = None,
samples: List[Dict] = None,
tokenizer: "TTSTokenizer" = None,
compute_f0: bool = False,
compute_energy: bool = False,
f0_cache_path: str = None,
energy_cache_path: str = None,
return_wav: bool = False,
batch_group_size: int = 0,
min_text_len: int = 0,
max_text_len: int = float("inf"),
min_audio_len: int = 0,
max_audio_len: int = float("inf"),
phoneme_cache_path: str = None,
precompute_num_workers: int = 0,
speaker_id_mapping: Dict = None,
d_vector_mapping: Dict = None,
language_id_mapping: Dict = None,
use_noise_augment: bool = False,
start_by_longest: bool = False,
verbose: bool = False,
):
"""Generic 📂 data loader for `tts` models. It is configurable for different outputs and needs.
If you need something different, you can subclass and override.
Args:
outputs_per_step (int): Number of time frames predicted per step.
compute_linear_spec (bool): compute linear spectrogram if True.
ap (TTS.tts.utils.AudioProcessor): Audio processor object.
samples (list): List of dataset samples.
tokenizer (TTSTokenizer): tokenizer to convert text to sequence IDs. If None init internally else
use the given. Defaults to None.
compute_f0 (bool): compute f0 if True. Defaults to False.
compute_energy (bool): compute energy if True. Defaults to False.
f0_cache_path (str): Path to store f0 cache. Defaults to None.
energy_cache_path (str): Path to store energy cache. Defaults to None.
return_wav (bool): Return the waveform of the sample. Defaults to False.
batch_group_size (int): Range of batch randomization after sorting
sequences by length. It shuffles each batch with bucketing to gather similar lenght sequences in a
batch. Set 0 to disable. Defaults to 0.
min_text_len (int): Minimum length of input text to be used. All shorter samples will be ignored.
Defaults to 0.
max_text_len (int): Maximum length of input text to be used. All longer samples will be ignored.
Defaults to float("inf").
min_audio_len (int): Minimum length of input audio to be used. All shorter samples will be ignored.
Defaults to 0.
max_audio_len (int): Maximum length of input audio to be used. All longer samples will be ignored.
The maximum length in the dataset defines the VRAM used in the training. Hence, pay attention to
this value if you encounter an OOM error in training. Defaults to float("inf").
phoneme_cache_path (str): Path to cache computed phonemes. It writes phonemes of each sample to a
separate file. Defaults to None.
precompute_num_workers (int): Number of workers to precompute features. Defaults to 0.
speaker_id_mapping (dict): Mapping of speaker names to IDs used to compute embedding vectors by the
embedding layer. Defaults to None.
d_vector_mapping (dict): Mapping of wav files to computed d-vectors. Defaults to None.
use_noise_augment (bool): Enable adding random noise to wav for augmentation. Defaults to False.
start_by_longest (bool): Start by longest sequence. It is especially useful to check OOM. Defaults to False.
verbose (bool): Print diagnostic information. Defaults to false.
"""
super().__init__()
self.batch_group_size = batch_group_size
self._samples = samples
self.outputs_per_step = outputs_per_step
self.compute_linear_spec = compute_linear_spec
self.return_wav = return_wav
self.compute_f0 = compute_f0
self.compute_energy = compute_energy
self.f0_cache_path = f0_cache_path
self.energy_cache_path = energy_cache_path
self.min_audio_len = min_audio_len
self.max_audio_len = max_audio_len
self.min_text_len = min_text_len
self.max_text_len = max_text_len
self.ap = ap
self.phoneme_cache_path = phoneme_cache_path
self.speaker_id_mapping = speaker_id_mapping
self.d_vector_mapping = d_vector_mapping
self.language_id_mapping = language_id_mapping
self.use_noise_augment = use_noise_augment
self.start_by_longest = start_by_longest
self.verbose = verbose
self.rescue_item_idx = 1
self.pitch_computed = False
self.tokenizer = tokenizer
if self.tokenizer.use_phonemes:
self.phoneme_dataset = PhonemeDataset(
self.samples, self.tokenizer, phoneme_cache_path, precompute_num_workers=precompute_num_workers
)
if compute_f0:
self.f0_dataset = F0Dataset(
self.samples, self.ap, cache_path=f0_cache_path, precompute_num_workers=precompute_num_workers
)
if compute_energy:
self.energy_dataset = EnergyDataset(
self.samples, self.ap, cache_path=energy_cache_path, precompute_num_workers=precompute_num_workers
)
if self.verbose:
self.print_logs()
@property
def lengths(self):
lens = []
for item in self.samples:
_, wav_file, *_ = _parse_sample(item)
audio_len = os.path.getsize(wav_file) / 16 * 8 # assuming 16bit audio
lens.append(audio_len)
return lens
@property
def samples(self):
return self._samples
@samples.setter
def samples(self, new_samples):
self._samples = new_samples
if hasattr(self, "f0_dataset"):
self.f0_dataset.samples = new_samples
if hasattr(self, "energy_dataset"):
self.energy_dataset.samples = new_samples
if hasattr(self, "phoneme_dataset"):
self.phoneme_dataset.samples = new_samples
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
return self.load_data(idx)
def print_logs(self, level: int = 0) -> None:
indent = "\t" * level
print("\n")
print(f"{indent}> DataLoader initialization")
print(f"{indent}| > Tokenizer:")
self.tokenizer.print_logs(level + 1)
print(f"{indent}| > Number of instances : {len(self.samples)}")
def load_wav(self, filename):
waveform = self.ap.load_wav(filename)
assert waveform.size > 0
return waveform
def get_phonemes(self, idx, text):
out_dict = self.phoneme_dataset[idx]
assert text == out_dict["text"], f"{text} != {out_dict['text']}"
assert len(out_dict["token_ids"]) > 0
return out_dict
def get_f0(self, idx):
out_dict = self.f0_dataset[idx]
item = self.samples[idx]
assert item["audio_unique_name"] == out_dict["audio_unique_name"]
return out_dict
def get_energy(self, idx):
out_dict = self.energy_dataset[idx]
item = self.samples[idx]
assert item["audio_unique_name"] == out_dict["audio_unique_name"]
return out_dict
@staticmethod
def get_attn_mask(attn_file):
return np.load(attn_file)
def get_token_ids(self, idx, text):
if self.tokenizer.use_phonemes:
token_ids = self.get_phonemes(idx, text)["token_ids"]
else:
token_ids = self.tokenizer.text_to_ids(text)
return np.array(token_ids, dtype=np.int32)
def load_data(self, idx):
item = self.samples[idx]
raw_text = item["text"]
wav = np.asarray(self.load_wav(item["audio_file"]), dtype=np.float32)
# apply noise for augmentation
if self.use_noise_augment:
wav = noise_augment_audio(wav)
# get token ids
token_ids = self.get_token_ids(idx, item["text"])
# get pre-computed attention maps
attn = None
if "alignment_file" in item:
attn = self.get_attn_mask(item["alignment_file"])
# after phonemization the text length may change
# this is a shareful 🤭 hack to prevent longer phonemes
# TODO: find a better fix
if len(token_ids) > self.max_text_len or len(wav) < self.min_audio_len:
self.rescue_item_idx += 1
return self.load_data(self.rescue_item_idx)
# get f0 values
f0 = None
if self.compute_f0:
f0 = self.get_f0(idx)["f0"]
energy = None
if self.compute_energy:
energy = self.get_energy(idx)["energy"]
sample = {
"raw_text": raw_text,
"token_ids": token_ids,
"wav": wav,
"pitch": f0,
"energy": energy,
"attn": attn,
"item_idx": item["audio_file"],
"speaker_name": item["speaker_name"],
"language_name": item["language"],
"wav_file_name": os.path.basename(item["audio_file"]),
"audio_unique_name": item["audio_unique_name"],
}
return sample
@staticmethod
def _compute_lengths(samples):
new_samples = []
for item in samples:
audio_length = os.path.getsize(item["audio_file"]) / 16 * 8 # assuming 16bit audio
text_lenght = len(item["text"])
item["audio_length"] = audio_length
item["text_length"] = text_lenght
new_samples += [item]
return new_samples
@staticmethod
def filter_by_length(lengths: List[int], min_len: int, max_len: int):
idxs = np.argsort(lengths) # ascending order
ignore_idx = []
keep_idx = []
for idx in idxs:
length = lengths[idx]
if length < min_len or length > max_len:
ignore_idx.append(idx)
else:
keep_idx.append(idx)
return ignore_idx, keep_idx
@staticmethod
def sort_by_length(samples: List[List]):
audio_lengths = [s["audio_length"] for s in samples]
idxs = np.argsort(audio_lengths) # ascending order
return idxs
@staticmethod
def create_buckets(samples, batch_group_size: int):
assert batch_group_size > 0
for i in range(len(samples) // batch_group_size):
offset = i * batch_group_size
end_offset = offset + batch_group_size
temp_items = samples[offset:end_offset]
random.shuffle(temp_items)
samples[offset:end_offset] = temp_items
return samples
@staticmethod
def _select_samples_by_idx(idxs, samples):
samples_new = []
for idx in idxs:
samples_new.append(samples[idx])
return samples_new
def preprocess_samples(self):
r"""Sort `items` based on text length or audio length in ascending order. Filter out samples out or the length
range.
"""
samples = self._compute_lengths(self.samples)
# sort items based on the sequence length in ascending order
text_lengths = [i["text_length"] for i in samples]
audio_lengths = [i["audio_length"] for i in samples]
text_ignore_idx, text_keep_idx = self.filter_by_length(text_lengths, self.min_text_len, self.max_text_len)
audio_ignore_idx, audio_keep_idx = self.filter_by_length(audio_lengths, self.min_audio_len, self.max_audio_len)
keep_idx = list(set(audio_keep_idx) & set(text_keep_idx))
ignore_idx = list(set(audio_ignore_idx) | set(text_ignore_idx))
samples = self._select_samples_by_idx(keep_idx, samples)
sorted_idxs = self.sort_by_length(samples)
if self.start_by_longest:
longest_idxs = sorted_idxs[-1]
sorted_idxs[-1] = sorted_idxs[0]
sorted_idxs[0] = longest_idxs
samples = self._select_samples_by_idx(sorted_idxs, samples)
if len(samples) == 0:
raise RuntimeError(" [!] No samples left")
# shuffle batch groups
# create batches with similar length items
# the larger the `batch_group_size`, the higher the length variety in a batch.
if self.batch_group_size > 0:
samples = self.create_buckets(samples, self.batch_group_size)
# update items to the new sorted items
audio_lengths = [s["audio_length"] for s in samples]
text_lengths = [s["text_length"] for s in samples]
self.samples = samples
if self.verbose:
print(" | > Preprocessing samples")
print(" | > Max text length: {}".format(np.max(text_lengths)))
print(" | > Min text length: {}".format(np.min(text_lengths)))
print(" | > Avg text length: {}".format(np.mean(text_lengths)))
print(" | ")
print(" | > Max audio length: {}".format(np.max(audio_lengths)))
print(" | > Min audio length: {}".format(np.min(audio_lengths)))
print(" | > Avg audio length: {}".format(np.mean(audio_lengths)))
print(f" | > Num. instances discarded samples: {len(ignore_idx)}")
print(" | > Batch group size: {}.".format(self.batch_group_size))
@staticmethod
def _sort_batch(batch, text_lengths):
"""Sort the batch by the input text length for RNN efficiency.
Args:
batch (Dict): Batch returned by `__getitem__`.
text_lengths (List[int]): Lengths of the input character sequences.
"""
text_lengths, ids_sorted_decreasing = torch.sort(torch.LongTensor(text_lengths), dim=0, descending=True)
batch = [batch[idx] for idx in ids_sorted_decreasing]
return batch, text_lengths, ids_sorted_decreasing
def collate_fn(self, batch):
r"""
Perform preprocessing and create a final data batch:
1. Sort batch instances by text-length
2. Convert Audio signal to features.
3. PAD sequences wrt r.
4. Load to Torch.
"""
# Puts each data field into a tensor with outer dimension batch size
if isinstance(batch[0], collections.abc.Mapping):
token_ids_lengths = np.array([len(d["token_ids"]) for d in batch])
# sort items with text input length for RNN efficiency
batch, token_ids_lengths, ids_sorted_decreasing = self._sort_batch(batch, token_ids_lengths)
# convert list of dicts to dict of lists
batch = {k: [dic[k] for dic in batch] for k in batch[0]}
# get language ids from language names
if self.language_id_mapping is not None:
language_ids = [self.language_id_mapping[ln] for ln in batch["language_name"]]
else:
language_ids = None
# get pre-computed d-vectors
if self.d_vector_mapping is not None:
embedding_keys = list(batch["audio_unique_name"])
d_vectors = [self.d_vector_mapping[w]["embedding"] for w in embedding_keys]
else:
d_vectors = None
# get numerical speaker ids from speaker names
if self.speaker_id_mapping:
speaker_ids = [self.speaker_id_mapping[sn] for sn in batch["speaker_name"]]
else:
speaker_ids = None
# compute features
mel = [self.ap.melspectrogram(w).astype("float32") for w in batch["wav"]]
mel_lengths = [m.shape[1] for m in mel]
# lengths adjusted by the reduction factor
mel_lengths_adjusted = [
m.shape[1] + (self.outputs_per_step - (m.shape[1] % self.outputs_per_step))
if m.shape[1] % self.outputs_per_step
else m.shape[1]
for m in mel
]
# compute 'stop token' targets
stop_targets = [np.array([0.0] * (mel_len - 1) + [1.0]) for mel_len in mel_lengths]
# PAD stop targets
stop_targets = prepare_stop_target(stop_targets, self.outputs_per_step)
# PAD sequences with longest instance in the batch
token_ids = prepare_data(batch["token_ids"]).astype(np.int32)
# PAD features with longest instance
mel = prepare_tensor(mel, self.outputs_per_step)
# B x D x T --> B x T x D
mel = mel.transpose(0, 2, 1)
# convert things to pytorch
token_ids_lengths = torch.LongTensor(token_ids_lengths)
token_ids = torch.LongTensor(token_ids)
mel = torch.FloatTensor(mel).contiguous()
mel_lengths = torch.LongTensor(mel_lengths)
stop_targets = torch.FloatTensor(stop_targets)
# speaker vectors
if d_vectors is not None:
d_vectors = torch.FloatTensor(d_vectors)
if speaker_ids is not None:
speaker_ids = torch.LongTensor(speaker_ids)
if language_ids is not None:
language_ids = torch.LongTensor(language_ids)
# compute linear spectrogram
linear = None
if self.compute_linear_spec:
linear = [self.ap.spectrogram(w).astype("float32") for w in batch["wav"]]
linear = prepare_tensor(linear, self.outputs_per_step)
linear = linear.transpose(0, 2, 1)
assert mel.shape[1] == linear.shape[1]
linear = torch.FloatTensor(linear).contiguous()
# format waveforms
wav_padded = None
if self.return_wav:
wav_lengths = [w.shape[0] for w in batch["wav"]]
max_wav_len = max(mel_lengths_adjusted) * self.ap.hop_length
wav_lengths = torch.LongTensor(wav_lengths)
wav_padded = torch.zeros(len(batch["wav"]), 1, max_wav_len)
for i, w in enumerate(batch["wav"]):
mel_length = mel_lengths_adjusted[i]
w = np.pad(w, (0, self.ap.hop_length * self.outputs_per_step), mode="edge")
w = w[: mel_length * self.ap.hop_length]
wav_padded[i, :, : w.shape[0]] = torch.from_numpy(w)
wav_padded.transpose_(1, 2)
# format F0
if self.compute_f0:
pitch = prepare_data(batch["pitch"])
assert mel.shape[1] == pitch.shape[1], f"[!] {mel.shape} vs {pitch.shape}"
pitch = torch.FloatTensor(pitch)[:, None, :].contiguous() # B x 1 xT
else:
pitch = None
# format energy
if self.compute_energy:
energy = prepare_data(batch["energy"])
assert mel.shape[1] == energy.shape[1], f"[!] {mel.shape} vs {energy.shape}"
energy = torch.FloatTensor(energy)[:, None, :].contiguous() # B x 1 xT
else:
energy = None
# format attention masks
attns = None
if batch["attn"][0] is not None:
attns = [batch["attn"][idx].T for idx in ids_sorted_decreasing]
for idx, attn in enumerate(attns):
pad2 = mel.shape[1] - attn.shape[1]
pad1 = token_ids.shape[1] - attn.shape[0]
assert pad1 >= 0 and pad2 >= 0, f"[!] Negative padding - {pad1} and {pad2}"
attn = np.pad(attn, [[0, pad1], [0, pad2]])
attns[idx] = attn
attns = prepare_tensor(attns, self.outputs_per_step)
attns = torch.FloatTensor(attns).unsqueeze(1)
return {
"token_id": token_ids,
"token_id_lengths": token_ids_lengths,
"speaker_names": batch["speaker_name"],
"linear": linear,
"mel": mel,
"mel_lengths": mel_lengths,
"stop_targets": stop_targets,
"item_idxs": batch["item_idx"],
"d_vectors": d_vectors,
"speaker_ids": speaker_ids,
"attns": attns,
"waveform": wav_padded,
"raw_text": batch["raw_text"],
"pitch": pitch,
"energy": energy,
"language_ids": language_ids,
"audio_unique_names": batch["audio_unique_name"],
}
raise TypeError(
(
"batch must contain tensors, numbers, dicts or lists;\
found {}".format(
type(batch[0])
)
)
)
class PhonemeDataset(Dataset):
"""Phoneme Dataset for converting input text to phonemes and then token IDs
At initialization, it pre-computes the phonemes under `cache_path` and loads them in training to reduce data
loading latency. If `cache_path` is already present, it skips the pre-computation.
Args:
samples (Union[List[List], List[Dict]]):
List of samples. Each sample is a list or a dict.
tokenizer (TTSTokenizer):
Tokenizer to convert input text to phonemes.
cache_path (str):
Path to cache phonemes. If `cache_path` is already present or None, it skips the pre-computation.
precompute_num_workers (int):
Number of workers used for pre-computing the phonemes. Defaults to 0.
"""
def __init__(
self,
samples: Union[List[Dict], List[List]],
tokenizer: "TTSTokenizer",
cache_path: str,
precompute_num_workers=0,
):
self.samples = samples
self.tokenizer = tokenizer
self.cache_path = cache_path
if cache_path is not None and not os.path.exists(cache_path):
os.makedirs(cache_path)
self.precompute(precompute_num_workers)
def __getitem__(self, index):
item = self.samples[index]
ids = self.compute_or_load(string2filename(item["audio_unique_name"]), item["text"], item["language"])
ph_hat = self.tokenizer.ids_to_text(ids)
return {"text": item["text"], "ph_hat": ph_hat, "token_ids": ids, "token_ids_len": len(ids)}
def __len__(self):
return len(self.samples)
def compute_or_load(self, file_name, text, language):
"""Compute phonemes for the given text.
If the phonemes are already cached, load them from cache.
"""
file_ext = "_phoneme.npy"
cache_path = os.path.join(self.cache_path, file_name + file_ext)
try:
ids = np.load(cache_path)
except FileNotFoundError:
ids = self.tokenizer.text_to_ids(text, language=language)
np.save(cache_path, ids)
return ids
def get_pad_id(self):
"""Get pad token ID for sequence padding"""
return self.tokenizer.pad_id
def precompute(self, num_workers=1):
"""Precompute phonemes for all samples.
We use pytorch dataloader because we are lazy.
"""
print("[*] Pre-computing phonemes...")
with tqdm.tqdm(total=len(self)) as pbar:
batch_size = num_workers if num_workers > 0 else 1
dataloder = torch.utils.data.DataLoader(
batch_size=batch_size, dataset=self, shuffle=False, num_workers=num_workers, collate_fn=self.collate_fn
)
for _ in dataloder:
pbar.update(batch_size)
def collate_fn(self, batch):
ids = [item["token_ids"] for item in batch]
ids_lens = [item["token_ids_len"] for item in batch]
texts = [item["text"] for item in batch]
texts_hat = [item["ph_hat"] for item in batch]
ids_lens_max = max(ids_lens)
ids_torch = torch.LongTensor(len(ids), ids_lens_max).fill_(self.get_pad_id())
for i, ids_len in enumerate(ids_lens):
ids_torch[i, :ids_len] = torch.LongTensor(ids[i])
return {"text": texts, "ph_hat": texts_hat, "token_ids": ids_torch}
def print_logs(self, level: int = 0) -> None:
indent = "\t" * level
print("\n")
print(f"{indent}> PhonemeDataset ")
print(f"{indent}| > Tokenizer:")
self.tokenizer.print_logs(level + 1)
print(f"{indent}| > Number of instances : {len(self.samples)}")
class F0Dataset:
"""F0 Dataset for computing F0 from wav files in CPU
Pre-compute F0 values for all the samples at initialization if `cache_path` is not None or already present. It
also computes the mean and std of F0 values if `normalize_f0` is True.
Args:
samples (Union[List[List], List[Dict]]):
List of samples. Each sample is a list or a dict.
ap (AudioProcessor):
AudioProcessor to compute F0 from wav files.
cache_path (str):
Path to cache F0 values. If `cache_path` is already present or None, it skips the pre-computation.
Defaults to None.
precompute_num_workers (int):
Number of workers used for pre-computing the F0 values. Defaults to 0.
normalize_f0 (bool):
Whether to normalize F0 values by mean and std. Defaults to True.
"""
def __init__(
self,
samples: Union[List[List], List[Dict]],
ap: "AudioProcessor",
audio_config=None, # pylint: disable=unused-argument
verbose=False,
cache_path: str = None,
precompute_num_workers=0,
normalize_f0=True,
):
self.samples = samples
self.ap = ap
self.verbose = verbose
self.cache_path = cache_path
self.normalize_f0 = normalize_f0
self.pad_id = 0.0
self.mean = None
self.std = None
if cache_path is not None and not os.path.exists(cache_path):
os.makedirs(cache_path)
self.precompute(precompute_num_workers)
if normalize_f0:
self.load_stats(cache_path)
def __getitem__(self, idx):
item = self.samples[idx]
f0 = self.compute_or_load(item["audio_file"], string2filename(item["audio_unique_name"]))
if self.normalize_f0:
assert self.mean is not None and self.std is not None, " [!] Mean and STD is not available"
f0 = self.normalize(f0)
return {"audio_unique_name": item["audio_unique_name"], "f0": f0}
def __len__(self):
return len(self.samples)
def precompute(self, num_workers=0):
print("[*] Pre-computing F0s...")
with tqdm.tqdm(total=len(self)) as pbar:
batch_size = num_workers if num_workers > 0 else 1
# we do not normalize at preproessing
normalize_f0 = self.normalize_f0
self.normalize_f0 = False
dataloder = torch.utils.data.DataLoader(
batch_size=batch_size, dataset=self, shuffle=False, num_workers=num_workers, collate_fn=self.collate_fn
)
computed_data = []
for batch in dataloder:
f0 = batch["f0"]
computed_data.append(f for f in f0)
pbar.update(batch_size)
self.normalize_f0 = normalize_f0
if self.normalize_f0:
computed_data = [tensor for batch in computed_data for tensor in batch] # flatten
pitch_mean, pitch_std = self.compute_pitch_stats(computed_data)
pitch_stats = {"mean": pitch_mean, "std": pitch_std}
np.save(os.path.join(self.cache_path, "pitch_stats"), pitch_stats, allow_pickle=True)
def get_pad_id(self):
return self.pad_id
@staticmethod
def create_pitch_file_path(file_name, cache_path):
pitch_file = os.path.join(cache_path, file_name + "_pitch.npy")
return pitch_file
@staticmethod
def _compute_and_save_pitch(ap, wav_file, pitch_file=None):
wav = ap.load_wav(wav_file)
pitch = ap.compute_f0(wav)
if pitch_file:
np.save(pitch_file, pitch)
return pitch
@staticmethod
def compute_pitch_stats(pitch_vecs):
nonzeros = np.concatenate([v[np.where(v != 0.0)[0]] for v in pitch_vecs])
mean, std = np.mean(nonzeros), np.std(nonzeros)
return mean, std
def load_stats(self, cache_path):
stats_path = os.path.join(cache_path, "pitch_stats.npy")
stats = np.load(stats_path, allow_pickle=True).item()
self.mean = stats["mean"].astype(np.float32)
self.std = stats["std"].astype(np.float32)
def normalize(self, pitch):
zero_idxs = np.where(pitch == 0.0)[0]
pitch = pitch - self.mean
pitch = pitch / self.std
pitch[zero_idxs] = 0.0
return pitch
def denormalize(self, pitch):
zero_idxs = np.where(pitch == 0.0)[0]
pitch *= self.std
pitch += self.mean
pitch[zero_idxs] = 0.0
return pitch
def compute_or_load(self, wav_file, audio_unique_name):
"""
compute pitch and return a numpy array of pitch values
"""
pitch_file = self.create_pitch_file_path(audio_unique_name, self.cache_path)
if not os.path.exists(pitch_file):
pitch = self._compute_and_save_pitch(self.ap, wav_file, pitch_file)
else:
pitch = np.load(pitch_file)
return pitch.astype(np.float32)
def collate_fn(self, batch):
audio_unique_name = [item["audio_unique_name"] for item in batch]
f0s = [item["f0"] for item in batch]
f0_lens = [len(item["f0"]) for item in batch]
f0_lens_max = max(f0_lens)
f0s_torch = torch.LongTensor(len(f0s), f0_lens_max).fill_(self.get_pad_id())
for i, f0_len in enumerate(f0_lens):
f0s_torch[i, :f0_len] = torch.LongTensor(f0s[i])
return {"audio_unique_name": audio_unique_name, "f0": f0s_torch, "f0_lens": f0_lens}
def print_logs(self, level: int = 0) -> None:
indent = "\t" * level
print("\n")
print(f"{indent}> F0Dataset ")
print(f"{indent}| > Number of instances : {len(self.samples)}")
class EnergyDataset:
"""Energy Dataset for computing Energy from wav files in CPU
Pre-compute Energy values for all the samples at initialization if `cache_path` is not None or already present. It
also computes the mean and std of Energy values if `normalize_Energy` is True.
Args:
samples (Union[List[List], List[Dict]]):
List of samples. Each sample is a list or a dict.
ap (AudioProcessor):
AudioProcessor to compute Energy from wav files.
cache_path (str):
Path to cache Energy values. If `cache_path` is already present or None, it skips the pre-computation.
Defaults to None.
precompute_num_workers (int):
Number of workers used for pre-computing the Energy values. Defaults to 0.
normalize_Energy (bool):
Whether to normalize Energy values by mean and std. Defaults to True.
"""
def __init__(
self,
samples: Union[List[List], List[Dict]],
ap: "AudioProcessor",
verbose=False,
cache_path: str = None,
precompute_num_workers=0,
normalize_energy=True,
):
self.samples = samples
self.ap = ap
self.verbose = verbose
self.cache_path = cache_path
self.normalize_energy = normalize_energy
self.pad_id = 0.0
self.mean = None
self.std = None
if cache_path is not None and not os.path.exists(cache_path):
os.makedirs(cache_path)
self.precompute(precompute_num_workers)
if normalize_energy:
self.load_stats(cache_path)
def __getitem__(self, idx):
item = self.samples[idx]
energy = self.compute_or_load(item["audio_file"], string2filename(item["audio_unique_name"]))
if self.normalize_energy:
assert self.mean is not None and self.std is not None, " [!] Mean and STD is not available"
energy = self.normalize(energy)
return {"audio_unique_name": item["audio_unique_name"], "energy": energy}
def __len__(self):
return len(self.samples)
def precompute(self, num_workers=0):
print("[*] Pre-computing energys...")
with tqdm.tqdm(total=len(self)) as pbar:
batch_size = num_workers if num_workers > 0 else 1
# we do not normalize at preproessing
normalize_energy = self.normalize_energy
self.normalize_energy = False
dataloder = torch.utils.data.DataLoader(
batch_size=batch_size, dataset=self, shuffle=False, num_workers=num_workers, collate_fn=self.collate_fn
)
computed_data = []
for batch in dataloder:
energy = batch["energy"]
computed_data.append(e for e in energy)
pbar.update(batch_size)
self.normalize_energy = normalize_energy
if self.normalize_energy:
computed_data = [tensor for batch in computed_data for tensor in batch] # flatten
energy_mean, energy_std = self.compute_energy_stats(computed_data)
energy_stats = {"mean": energy_mean, "std": energy_std}
np.save(os.path.join(self.cache_path, "energy_stats"), energy_stats, allow_pickle=True)
def get_pad_id(self):
return self.pad_id
@staticmethod
def create_energy_file_path(wav_file, cache_path):
file_name = os.path.splitext(os.path.basename(wav_file))[0]
energy_file = os.path.join(cache_path, file_name + "_energy.npy")
return energy_file
@staticmethod
def _compute_and_save_energy(ap, wav_file, energy_file=None):
wav = ap.load_wav(wav_file)
energy = calculate_energy(wav, fft_size=ap.fft_size, hop_length=ap.hop_length, win_length=ap.win_length)
if energy_file:
np.save(energy_file, energy)
return energy
@staticmethod
def compute_energy_stats(energy_vecs):
nonzeros = np.concatenate([v[np.where(v != 0.0)[0]] for v in energy_vecs])
mean, std = np.mean(nonzeros), np.std(nonzeros)
return mean, std
def load_stats(self, cache_path):
stats_path = os.path.join(cache_path, "energy_stats.npy")
stats = np.load(stats_path, allow_pickle=True).item()
self.mean = stats["mean"].astype(np.float32)
self.std = stats["std"].astype(np.float32)
def normalize(self, energy):
zero_idxs = np.where(energy == 0.0)[0]
energy = energy - self.mean
energy = energy / self.std
energy[zero_idxs] = 0.0
return energy
def denormalize(self, energy):
zero_idxs = np.where(energy == 0.0)[0]
energy *= self.std
energy += self.mean
energy[zero_idxs] = 0.0
return energy
def compute_or_load(self, wav_file, audio_unique_name):
"""
compute energy and return a numpy array of energy values
"""
energy_file = self.create_energy_file_path(audio_unique_name, self.cache_path)
if not os.path.exists(energy_file):
energy = self._compute_and_save_energy(self.ap, wav_file, energy_file)
else:
energy = np.load(energy_file)
return energy.astype(np.float32)
def collate_fn(self, batch):
audio_unique_name = [item["audio_unique_name"] for item in batch]
energys = [item["energy"] for item in batch]
energy_lens = [len(item["energy"]) for item in batch]
energy_lens_max = max(energy_lens)
energys_torch = torch.LongTensor(len(energys), energy_lens_max).fill_(self.get_pad_id())
for i, energy_len in enumerate(energy_lens):
energys_torch[i, :energy_len] = torch.LongTensor(energys[i])
return {"audio_unique_name": audio_unique_name, "energy": energys_torch, "energy_lens": energy_lens}
def print_logs(self, level: int = 0) -> None:
indent = "\t" * level
print("\n")
print(f"{indent}> energyDataset ")
print(f"{indent}| > Number of instances : {len(self.samples)}")
| 0 |
coqui_public_repos/STT/native_client/kenlm | coqui_public_repos/STT/native_client/kenlm/util/probing_hash_table_benchmark_main.cc | #include "file.hh"
#include "probing_hash_table.hh"
#include "mmap.hh"
#include "usage.hh"
#include "thread_pool.hh"
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#ifdef WIN32
#include <windows.h>
#include <processthreadsapi.h>
#else
#include <sys/resource.h>
#include <sys/time.h>
#endif
#include <iostream>
namespace util {
namespace {
struct Entry {
typedef uint64_t Key;
Key key;
Key GetKey() const { return key; }
};
// I don't care if this doesn't run on Windows. Empirically /dev/urandom was faster than boost::random's Mersenne Twister.
class URandom {
public:
URandom() :
it_(buf_ + 1024), end_(buf_ + 1024),
file_(util::OpenReadOrThrow("/dev/urandom")) {}
uint64_t Get() {
if (it_ == end_) {
it_ = buf_;
util::ReadOrThrow(file_.get(), buf_, sizeof(buf_));
it_ = buf_;
}
return *it_++;
}
void Batch(uint64_t *begin, uint64_t *end) {
util::ReadOrThrow(file_.get(), begin, (end - begin) * sizeof(uint64_t));
}
private:
uint64_t buf_[1024];
uint64_t *it_, *end_;
util::scoped_fd file_;
};
struct PrefetchEntry {
uint64_t key;
const Entry *pointer;
};
template <class TableT, unsigned PrefetchSize> class PrefetchQueue {
public:
typedef TableT Table;
explicit PrefetchQueue(Table &table) : table_(table), cur_(0), twiddle_(false) {
for (PrefetchEntry *i = entries_; i != entries_ + PrefetchSize; ++i)
i->pointer = NULL;
}
void Add(uint64_t key) {
if (Cur().pointer) {
twiddle_ ^= table_.FindFromIdeal(Cur().key, Cur().pointer);
}
Cur().key = key;
Cur().pointer = table_.Ideal(key);
__builtin_prefetch(Cur().pointer, 0, 0);
Next();
}
bool Drain() {
if (Cur().pointer) {
for (PrefetchEntry *i = &Cur(); i < entries_ + PrefetchSize; ++i) {
twiddle_ ^= table_.FindFromIdeal(i->key, i->pointer);
}
}
for (PrefetchEntry *i = entries_; i < &Cur(); ++i) {
twiddle_ ^= table_.FindFromIdeal(i->key, i->pointer);
}
return twiddle_;
}
private:
PrefetchEntry &Cur() { return entries_[cur_]; }
void Next() {
++cur_;
cur_ = cur_ % PrefetchSize;
}
Table &table_;
PrefetchEntry entries_[PrefetchSize];
std::size_t cur_;
bool twiddle_;
PrefetchQueue(const PrefetchQueue&);
void operator=(const PrefetchQueue&);
};
template <class TableT> class Immediate {
public:
typedef TableT Table;
explicit Immediate(Table &table) : table_(table), twiddle_(false) {}
void Add(uint64_t key) {
typename Table::ConstIterator it;
twiddle_ ^= table_.Find(key, it);
}
bool Drain() const { return twiddle_; }
private:
Table &table_;
bool twiddle_;
};
std::size_t Size(uint64_t entries, float multiplier = 1.5) {
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, Power2Mod> Table;
// Always round up to power of 2 for fair comparison.
return Power2Mod::RoundBuckets(Table::Size(entries, multiplier) / sizeof(Entry)) * sizeof(Entry);
}
template <class Queue> bool Test(URandom &rn, uint64_t entries, const uint64_t *const queries_begin, const uint64_t *const queries_end, bool ordinary_malloc, float multiplier = 1.5) {
std::size_t size = Size(entries, multiplier);
scoped_memory backing;
if (ordinary_malloc) {
backing.reset(util::CallocOrThrow(size), size, scoped_memory::MALLOC_ALLOCATED);
} else {
util::HugeMalloc(size, true, backing);
}
typename Queue::Table table(backing.get(), size);
double start = CPUTime();
for (uint64_t i = 0; i < entries; ++i) {
Entry entry;
entry.key = rn.Get();
table.Insert(entry);
}
double inserted = CPUTime() - start;
double before_lookup = CPUTime();
Queue queue(table);
for (const uint64_t *i = queries_begin; i != queries_end; ++i) {
queue.Add(*i);
}
bool meaningless = queue.Drain();
std::cout << ' ' << (inserted / static_cast<double>(entries)) << ' ' << (CPUTime() - before_lookup) / static_cast<double>(queries_end - queries_begin) << std::flush;
return meaningless;
}
bool TestRun(uint64_t lookups = 20000000, float multiplier = 1.5) {
URandom rn;
util::scoped_memory queries;
HugeMalloc(lookups * sizeof(uint64_t), true, queries);
rn.Batch(static_cast<uint64_t*>(queries.get()), static_cast<uint64_t*>(queries.get()) + lookups);
uint64_t physical_mem_limit = util::GuessPhysicalMemory() / 2;
bool meaningless = true;
for (uint64_t i = 4; Size(i / multiplier) < physical_mem_limit; i *= 4) {
std::cout << static_cast<std::size_t>(i / multiplier) << ' ' << Size(i / multiplier);
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, Power2Mod> Table;
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, DivMod> TableDiv;
const uint64_t *const queries_begin = static_cast<const uint64_t*>(queries.get());
meaningless ^= util::Test<Immediate<TableDiv> >(rn, i / multiplier, queries_begin, queries_begin + lookups, true, multiplier);
meaningless ^= util::Test<Immediate<Table> >(rn, i / multiplier, queries_begin, queries_begin + lookups, true, multiplier);
meaningless ^= util::Test<PrefetchQueue<Table, 4> >(rn, i / multiplier, queries_begin, queries_begin + lookups, true, multiplier);
meaningless ^= util::Test<Immediate<Table> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
meaningless ^= util::Test<PrefetchQueue<Table, 2> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
meaningless ^= util::Test<PrefetchQueue<Table, 4> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
meaningless ^= util::Test<PrefetchQueue<Table, 8> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
meaningless ^= util::Test<PrefetchQueue<Table, 16> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
std::cout << std::endl;
}
return meaningless;
}
template<class Table>
struct ParallelTestRequest{
ParallelTestRequest() : queries_begin_(NULL), queries_end_(NULL), table_(NULL) {}
ParallelTestRequest(const uint64_t *queries_begin, const uint64_t *queries_end, Table *table) :
queries_begin_(queries_begin),
queries_end_(queries_end),
table_(table) {}
bool operator==(const ParallelTestRequest &rhs) const {
return this->queries_begin_ == rhs.queries_begin_ && this->queries_end_ == rhs.queries_end_;
}
const uint64_t *queries_begin_;
const uint64_t *queries_end_;
Table * table_;
};
template <class TableT>
struct ParallelTestConstruct{
ParallelTestConstruct(boost::mutex& lock, const uint64_t* const burn_begin, const uint64_t* const burn_end, TableT* table) : lock_(lock), burn_begin_(burn_begin), burn_end_(burn_end), table_(table){}
boost::mutex& lock_;
const uint64_t* const burn_begin_;
const uint64_t* const burn_end_;
TableT* table_;
};
template<class Queue>
struct ParallelTestHandler{
typedef ParallelTestRequest<typename Queue::Table> Request;
explicit ParallelTestHandler(const ParallelTestConstruct<typename Queue::Table>& construct) : lock_(construct.lock_), totalTime_(0.0), nRequests_(0), nQueries_(0), error_(false), twiddle_(false){
//perform initial burn
for(const uint64_t* i = construct.burn_begin_; i < construct.burn_end_; i++){
typename Queue::Table::ConstIterator it;
twiddle_ ^= construct.table_->Find(*i, it);
}
}
void operator()(Request request){
if (error_) return;
Queue queue(*request.table_);
double start = ThreadTime();
if(start < 0.0){
error_ = true;
return;
}
for(const uint64_t *i = request.queries_begin_; i != request.queries_end_; ++i){
queue.Add(*i);
}
twiddle_ ^= queue.Drain();
double end = ThreadTime();
if(end < 0.0){
error_ = true;
return;
}
totalTime_ += end - start;
nQueries_ += request.queries_end_ - request.queries_begin_;
++nRequests_;
}
virtual ~ParallelTestHandler() {
boost::unique_lock<boost::mutex> produce_lock(lock_);
if (error_){
std::cout << "Error ";
}
else {
std::cout << nRequests_ << ' ' << ' ' << nQueries_ << ' ' << totalTime_ << std::endl;
}
std::cerr << "Meaningless " << twiddle_ << std::endl;
}
private:
boost::mutex &lock_;
double totalTime_;
std::size_t nRequests_;
std::size_t nQueries_;
bool error_;
bool twiddle_;
};
template<class Queue>
void ParallelTest(typename Queue::Table* table, const uint64_t *const queries_begin,
const uint64_t *const queries_end, std::size_t num_threads,
std::size_t tasks_per_thread, std::size_t burn){
boost::mutex lock;
ParallelTestConstruct<typename Queue::Table> construct(lock, queries_begin, queries_begin + burn, table);
ParallelTestRequest<typename Queue::Table> poison(NULL, NULL, NULL);
{
util::ThreadPool<ParallelTestHandler<Queue> > pool(num_threads, num_threads, construct, poison);
const uint64_t queries_per_thread =(static_cast<uint64_t>(queries_end-queries_begin-burn)/num_threads)/tasks_per_thread;
for (const uint64_t *i = queries_begin+burn; i + queries_per_thread <= queries_end; i += queries_per_thread){
ParallelTestRequest<typename Queue::Table> request(i, i+queries_per_thread, table);
pool.Produce(request);
}
} // pool gets deallocated and all jobs finish
std::cout << std::endl;
}
void ParallelTestRun(std::size_t tasks_per_thread = 1, std::size_t burn = 4000, uint64_t lookups = 20000000, float multiplier = 1.5) {
URandom rn;
util::scoped_memory queries;
HugeMalloc((lookups + burn)* sizeof(uint64_t), true, queries);
rn.Batch(static_cast<uint64_t*>(queries.get()), static_cast<uint64_t*>(queries.get()) + lookups + burn);
const uint64_t *const queries_begin = static_cast<const uint64_t*>(queries.get());
const uint64_t *const queries_end = queries_begin + lookups + burn;
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, Power2Mod> Table;
uint64_t physical_mem_limit = util::GuessPhysicalMemory() / 2;
for (uint64_t i = 4; Size(i / multiplier, multiplier) < physical_mem_limit; i *= 4) {
std::size_t entries = static_cast<std::size_t>(i / multiplier);
std::size_t size = Size(i/multiplier, multiplier);
scoped_memory backing;
util::HugeMalloc(size, true, backing);
Table table(backing.get(), size);
for (uint64_t j = 0; j < entries; ++j) {
Entry entry;
entry.key = rn.Get();
table.Insert(entry);
}
for(std::size_t num_threads = 1; num_threads <= 16; num_threads*=2){
std::cout << entries << ' ' << size << ' ' << num_threads << ' ' << std::endl;
util::ParallelTest<Immediate<Table> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
util::ParallelTest<PrefetchQueue<Table, 2> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
util::ParallelTest<PrefetchQueue<Table, 4> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
util::ParallelTest<PrefetchQueue<Table, 8> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
util::ParallelTest<PrefetchQueue<Table, 16> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
}
}
}
} // namespace
} // namespace util
int main() {
//bool meaningless = false;
std::cout << "#CPU time\n";
//meaningless ^= util::TestRun();
util::ParallelTestRun(10, 4000);
//std::cerr << "Meaningless: " << meaningless << '\n';
}
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/add-on.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// FST implementation class to attach an arbitrary object with a read/write
// method to an FST and its file representation. The FST is given a new type
// name.
#ifndef FST_ADD_ON_H_
#define FST_ADD_ON_H_
#include <stddef.h>
#include <memory>
#include <string>
#include <utility>
#include <fst/log.h>
#include <fst/fst.h>
namespace fst {
// Identifies stream data as an add-on FST.
static constexpr int32_t kAddOnMagicNumber = 446681434;
// Nothing to save.
class NullAddOn {
public:
NullAddOn() {}
static NullAddOn *Read(std::istream &strm, const FstReadOptions &opts) {
return new NullAddOn();
}
bool Write(std::ostream &ostrm, const FstWriteOptions &opts) const {
return true;
}
};
// Create a new add-on from a pair of add-ons.
template <class A1, class A2>
class AddOnPair {
public:
// Argument reference count incremented.
AddOnPair(std::shared_ptr<A1> a1, std::shared_ptr<A2> a2)
: a1_(std::move(a1)), a2_(std::move(a2)) {}
const A1 *First() const { return a1_.get(); }
const A2 *Second() const { return a2_.get(); }
std::shared_ptr<A1> SharedFirst() const { return a1_; }
std::shared_ptr<A2> SharedSecond() const { return a2_; }
static AddOnPair<A1, A2> *Read(std::istream &istrm,
const FstReadOptions &opts) {
A1 *a1 = nullptr;
bool have_addon1 = false;
ReadType(istrm, &have_addon1);
if (have_addon1) a1 = A1::Read(istrm, opts);
A2 *a2 = nullptr;
bool have_addon2 = false;
ReadType(istrm, &have_addon2);
if (have_addon2) a2 = A2::Read(istrm, opts);
return new AddOnPair<A1, A2>(std::shared_ptr<A1>(a1),
std::shared_ptr<A2>(a2));
}
bool Write(std::ostream &ostrm, const FstWriteOptions &opts) const {
bool have_addon1 = a1_ != nullptr;
WriteType(ostrm, have_addon1);
if (have_addon1) a1_->Write(ostrm, opts);
bool have_addon2 = a2_ != nullptr;
WriteType(ostrm, have_addon2);
if (have_addon2) a2_->Write(ostrm, opts);
return true;
}
private:
std::shared_ptr<A1> a1_;
std::shared_ptr<A2> a2_;
};
namespace internal {
// Adds an object of type T to an FST. T must support:
//
// T* Read(std::istream &);
// bool Write(std::ostream &);
//
// The resulting type is a new FST implementation.
template <class FST, class T>
class AddOnImpl : public FstImpl<typename FST::Arc> {
public:
using Arc = typename FST::Arc;
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
using FstImpl<Arc>::SetType;
using FstImpl<Arc>::SetInputSymbols;
using FstImpl<Arc>::SetOutputSymbols;
using FstImpl<Arc>::SetProperties;
using FstImpl<Arc>::WriteHeader;
// We make a thread-safe copy of the FST by default since an FST
// implementation is expected to not share mutable data between objects.
AddOnImpl(const FST &fst, const string &type,
std::shared_ptr<T> t = std::shared_ptr<T>())
: fst_(fst, true), t_(std::move(t)) {
SetType(type);
SetProperties(fst_.Properties(kFstProperties, false));
SetInputSymbols(fst_.InputSymbols());
SetOutputSymbols(fst_.OutputSymbols());
}
// Conversion from const Fst<Arc> & to F always copies the underlying
// implementation.
AddOnImpl(const Fst<Arc> &fst, const string &type,
std::shared_ptr<T> t = std::shared_ptr<T>())
: fst_(fst), t_(std::move(t)) {
SetType(type);
SetProperties(fst_.Properties(kFstProperties, false));
SetInputSymbols(fst_.InputSymbols());
SetOutputSymbols(fst_.OutputSymbols());
}
// We make a thread-safe copy of the FST by default since an FST
// implementation is expected to not share mutable data between objects.
AddOnImpl(const AddOnImpl<FST, T> &impl)
: fst_(impl.fst_, true), t_(impl.t_) {
SetType(impl.Type());
SetProperties(fst_.Properties(kCopyProperties, false));
SetInputSymbols(fst_.InputSymbols());
SetOutputSymbols(fst_.OutputSymbols());
}
StateId Start() const { return fst_.Start(); }
Weight Final(StateId s) const { return fst_.Final(s); }
size_t NumArcs(StateId s) const { return fst_.NumArcs(s); }
size_t NumInputEpsilons(StateId s) const { return fst_.NumInputEpsilons(s); }
size_t NumOutputEpsilons(StateId s) const {
return fst_.NumOutputEpsilons(s);
}
size_t NumStates() const { return fst_.NumStates(); }
static AddOnImpl<FST, T> *Read(std::istream &strm,
const FstReadOptions &opts) {
FstReadOptions nopts(opts);
FstHeader hdr;
if (!nopts.header) {
hdr.Read(strm, nopts.source);
nopts.header = &hdr;
}
std::unique_ptr<AddOnImpl<FST, T>> impl(
new AddOnImpl<FST, T>(nopts.header->FstType()));
if (!impl->ReadHeader(strm, nopts, kMinFileVersion, &hdr)) return nullptr;
impl.reset();
int32_t magic_number = 0;
ReadType(strm, &magic_number); // Ensures this is an add-on FST.
if (magic_number != kAddOnMagicNumber) {
LOG(ERROR) << "AddOnImpl::Read: Bad add-on header: " << nopts.source;
return nullptr;
}
FstReadOptions fopts(opts);
fopts.header = nullptr; // Contained header was written out.
std::unique_ptr<FST> fst(FST::Read(strm, fopts));
if (!fst) return nullptr;
std::shared_ptr<T> t;
bool have_addon = false;
ReadType(strm, &have_addon);
if (have_addon) { // Reads add-on object if present.
t = std::shared_ptr<T>(T::Read(strm, fopts));
if (!t) return nullptr;
}
return new AddOnImpl<FST, T>(*fst, nopts.header->FstType(), t);
}
bool Write(std::ostream &strm, const FstWriteOptions &opts) const {
FstHeader hdr;
FstWriteOptions nopts(opts);
nopts.write_isymbols = false; // Allows contained FST to hold any symbols.
nopts.write_osymbols = false;
WriteHeader(strm, nopts, kFileVersion, &hdr);
WriteType(strm, kAddOnMagicNumber); // Ensures this is an add-on FST.
FstWriteOptions fopts(opts);
fopts.write_header = true; // Forces writing contained header.
if (!fst_.Write(strm, fopts)) return false;
bool have_addon = !!t_;
WriteType(strm, have_addon);
// Writes add-on object if present.
if (have_addon) t_->Write(strm, opts);
return true;
}
void InitStateIterator(StateIteratorData<Arc> *data) const {
fst_.InitStateIterator(data);
}
void InitArcIterator(StateId s, ArcIteratorData<Arc> *data) const {
fst_.InitArcIterator(s, data);
}
FST &GetFst() { return fst_; }
const FST &GetFst() const { return fst_; }
const T *GetAddOn() const { return t_.get(); }
std::shared_ptr<T> GetSharedAddOn() const { return t_; }
void SetAddOn(std::shared_ptr<T> t) { t_ = t; }
private:
explicit AddOnImpl(const string &type) : t_() {
SetType(type);
SetProperties(kExpanded);
}
// Current file format version.
static constexpr int kFileVersion = 1;
// Minimum file format version supported.
static constexpr int kMinFileVersion = 1;
FST fst_;
std::shared_ptr<T> t_;
AddOnImpl &operator=(const AddOnImpl &) = delete;
};
template <class FST, class T>
constexpr int AddOnImpl<FST, T>::kFileVersion;
template <class FST, class T>
constexpr int AddOnImpl<FST, T>::kMinFileVersion;
} // namespace internal
} // namespace fst
#endif // FST_ADD_ON_H_
| 0 |
coqui_public_repos | coqui_public_repos/TTS/CITATION.cff | cff-version: 1.2.0
message: "If you want to cite 🐸💬, feel free to use this (but only if you loved it 😊)"
title: "Coqui TTS"
abstract: "A deep learning toolkit for Text-to-Speech, battle-tested in research and production"
date-released: 2021-01-01
authors:
- family-names: "Eren"
given-names: "Gölge"
- name: "The Coqui TTS Team"
version: 1.4
doi: 10.5281/zenodo.6334862
license: "MPL-2.0"
url: "https://www.coqui.ai"
repository-code: "https://github.com/coqui-ai/TTS"
keywords:
- machine learning
- deep learning
- artificial intelligence
- text to speech
- TTS | 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/lib/weight.cc | #include <fst/weight.h>
DEFINE_string(fst_weight_separator, ",",
"Character separator between printed composite weights; "
"must be a single character");
DEFINE_string(fst_weight_parentheses, "",
"Characters enclosing the first weight of a printed composite "
"weight (e.g., pair weight, tuple weight and derived classes) to "
"ensure proper I/O of nested composite weights; "
"must have size 0 (none) or 2 (open and close parenthesis)");
namespace fst {
namespace internal {
CompositeWeightIO::CompositeWeightIO(char separator,
std::pair<char, char> parentheses)
: separator_(separator),
open_paren_(parentheses.first),
close_paren_(parentheses.second),
error_(false) {
if ((open_paren_ == 0 || close_paren_ == 0) && open_paren_ != close_paren_) {
FSTERROR() << "Invalid configuration of weight parentheses: "
<< static_cast<int>(open_paren_) << " "
<< static_cast<int>(close_paren_);
error_ = true;
}
}
CompositeWeightIO::CompositeWeightIO()
: CompositeWeightIO(FLAGS_fst_weight_separator.empty()
? 0
: FLAGS_fst_weight_separator.front(),
{FLAGS_fst_weight_parentheses.empty()
? 0
: FLAGS_fst_weight_parentheses[0],
FLAGS_fst_weight_parentheses.size() < 2
? 0
: FLAGS_fst_weight_parentheses[1]}) {
if (FLAGS_fst_weight_separator.size() != 1) {
FSTERROR() << "CompositeWeight: "
<< "FLAGS_fst_weight_separator.size() is not equal to 1";
error_ = true;
}
if (!FLAGS_fst_weight_parentheses.empty() &&
FLAGS_fst_weight_parentheses.size() != 2) {
FSTERROR() << "CompositeWeight: "
<< "FLAGS_fst_weight_parentheses.size() is not equal to 2";
error_ = true;
}
}
} // namespace internal
CompositeWeightWriter::CompositeWeightWriter(std::ostream &ostrm)
: ostrm_(ostrm) {
if (error()) ostrm.clear(std::ios::badbit);
}
CompositeWeightWriter::CompositeWeightWriter(std::ostream &ostrm,
char separator,
std::pair<char, char> parentheses)
: internal::CompositeWeightIO(separator, parentheses), ostrm_(ostrm) {
if (error()) ostrm_.clear(std::ios::badbit);
}
void CompositeWeightWriter::WriteBegin() {
if (open_paren_ != 0) {
ostrm_ << open_paren_;
}
}
void CompositeWeightWriter::WriteEnd() {
if (close_paren_ != 0) {
ostrm_ << close_paren_;
}
}
CompositeWeightReader::CompositeWeightReader(std::istream &istrm)
: istrm_(istrm) {
if (error()) istrm_.clear(std::ios::badbit);
}
CompositeWeightReader::CompositeWeightReader(std::istream &istrm,
char separator,
std::pair<char, char> parentheses)
: internal::CompositeWeightIO(separator, parentheses), istrm_(istrm) {
if (error()) istrm_.clear(std::ios::badbit);
}
void CompositeWeightReader::ReadBegin() {
do { // Skips whitespace.
c_ = istrm_.get();
} while (std::isspace(c_));
if (open_paren_ != 0) {
if (c_ != open_paren_) {
FSTERROR() << "CompositeWeightReader: Open paren missing: "
<< "fst_weight_parentheses flag set correcty?";
istrm_.clear(std::ios::badbit);
return;
}
++depth_;
c_ = istrm_.get();
}
}
void CompositeWeightReader::ReadEnd() {
if (c_ != EOF && !std::isspace(c_)) {
FSTERROR() << "CompositeWeightReader: excess character: '"
<< static_cast<char>(c_)
<< "': fst_weight_parentheses flag set correcty?";
istrm_.clear(std::ios::badbit);
}
}
} // namespace fst
| 0 |
coqui_public_repos/coqui-py | coqui_public_repos/coqui-py/coqui/__main__.py | import asyncio
import csv
import json
import os
import shutil
import subprocess
import sys
import tempfile
from datetime import date, datetime
from functools import wraps
import click
from . import ClonedVoice, Coqui, Sample
def coroutine(f):
@wraps(f)
def wrapper(*args, **kwargs):
return asyncio.run(f(*args, **kwargs))
return wrapper
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError("Type %s not serializable" % type(obj))
class PersistedConfig:
def __init__(self, path):
self._path = os.path.expanduser(path)
self._value = self._read()
os.makedirs(os.path.dirname(self._path), exist_ok=True)
def set(self, value):
self._value = value
with open(self._path, "w") as fout:
json.dump(value, fout, indent=2)
def get(self):
return self._value
def _read(self):
if not os.path.exists(self._path):
return None
with open(self._path) as fin:
return json.load(fin)
BASE_URL = None
AuthInfo = PersistedConfig("~/.coqui/credentials")
@click.group()
@click.option("--base-url", default=None)
def main(base_url):
global BASE_URL
BASE_URL = base_url
@main.command()
@click.option("--token", help="API token to sign in with")
@coroutine
async def login(token):
coqui = Coqui(base_url=BASE_URL)
if await coqui.login(token):
AuthInfo.set(token)
click.echo("Logged in!")
else:
click.echo("Error: Invalid token!")
@main.group()
def tts():
pass
@tts.command()
@click.option(
"--fields",
help=f"CSV output, specify which attributes of the available cloned voices to print. Comma separated list, eg: -f id,name. Available fields: {', '.join(ClonedVoice._fields)}",
)
@click.option("--json", "json_out", is_flag=True, help="Print output as JSON")
@coroutine
async def list_voices(fields, json_out):
coqui = Coqui(base_url=BASE_URL)
await coqui.login(AuthInfo.get())
voices = await coqui.cloned_voices()
if json_out:
click.echo(json.dumps([v._asdict() for v in voices], default=json_serial))
elif not fields:
for v in voices:
print(v)
else:
writer = csv.writer(sys.stdout, lineterminator=os.linesep)
for v in voices:
writer.writerow([getattr(v, f) for f in fields.split(",")])
@tts.command()
@click.option("--audio_file", help="Path of reference audio file to clone voice from")
@click.option("--name", help="Name of cloned voice")
@click.option("--json", "json_out", is_flag=True, help="Print output as JSON")
@coroutine
async def clone_voice(audio_file, name, json_out):
coqui = Coqui(base_url=BASE_URL)
await coqui.login(AuthInfo.get())
with open(audio_file, "rb") as fin:
voice = await coqui.clone_voice(fin, name)
if json_out:
click.echo(json.dumps(voice._asdict(), default=json_serial))
else:
click.echo(voice)
@tts.command()
@click.option("--audio_file", help="Path of reference audio file to clone voice from")
@click.option(
"--audio_url", help="URL of reference audio file to estimate quality from"
)
@click.option("--json", "json_out", is_flag=True, help="Print output as JSON")
@coroutine
async def estimate_quality(audio_file, audio_url, json_out):
coqui = Coqui(base_url=BASE_URL)
await coqui.login(AuthInfo.get())
if not audio_file and not audio_url:
raise click.UsageError("Must specify exactly one of: audio_file or audio_url")
quality, raw = await coqui.estimate_quality(
audio_url=audio_url, audio_path=audio_file
)
if json_out:
click.echo(json.dumps({"quality": quality, "raw": raw}, default=json_serial))
else:
click.echo(f"Quality: {quality}\nRaw: {raw}")
@tts.command()
@click.option("--voice", help="ID of voice to list existing samples for")
@click.option(
"--fields",
"-f",
help=f"CSV output, speicfy which attributes of the available samples to print out. Comma separated list, eg: -f id,name. Available fields: {', '.join(Sample._fields)}",
)
@click.option("--json", "json_out", is_flag=True, help="Print output as JSON")
@coroutine
async def list_samples(voice, fields, json_out):
coqui = Coqui(base_url=BASE_URL)
await coqui.login(AuthInfo.get())
samples = await coqui.list_samples(voice_id=voice)
if json_out:
click.echo(json.dumps([s._asdict() for s in samples], default=json_serial))
elif not fields:
click.echo(samples)
else:
writer = csv.writer(sys.stdout, lineterminator=os.linesep)
for s in samples:
writer.writerow([getattr(s, f) for f in fields.split(",")])
@tts.command()
@click.option("--voice", help="ID of voice to synthesize", type=click.UUID)
@click.option("--text", help="Text to synthesize")
@click.option("--speed", help="Speed parameter for synthesis", default=1.0)
@click.option("--name", help="Name of sample", default=None)
@click.option(
"--save",
help="If specified, save the synthesized sample to this file name.",
default=None,
)
@click.option(
"--play",
help="If specified, play the synthesized sample",
is_flag=True,
)
@click.option("--json", "json_out", is_flag=True, help="Print output as JSON")
@coroutine
async def synthesize(voice, text, speed, name, save, play, json_out):
coqui = Coqui(base_url=BASE_URL)
await coqui.login(AuthInfo.get())
sample = await coqui.synthesize(voice, text, speed, name or text[:30])
# sample = {'id': '62151ee3-858f-4398-935d-e48481263927', 'name': 'test from the command line', 'created_at': '2022-06-14T20:15:33.016Z', 'voice_id': 'c97d34da-a677-4219-b4b2-9ec198c948e0', 'audio_url': 'https://coqui-dev-creator-app-synthesized-samples.s3.amazonaws.com/samples/sample_GAh7vFe.wav?AWSAccessKeyId=AKIAXW7NFYT5F2KY3J4D&Signature=CCz46wpRIHrkBT9TCx4vZMVkAQE%3D&Expires=1655241335'}
with tempfile.NamedTemporaryFile("wb") as fout:
await sample.download(fout)
if save:
shutil.copy(fout.name, save)
click.echo(f"Saved synthesized sample to {save}")
elif play:
subprocess.run(
["play", fout.name],
check=True,
stdin=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
elif json_out:
click.echo(json.dumps(sample._asdict(), default=json_serial))
else:
click.echo(sample)
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/extensions | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/extensions/far/farcreate.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Creates a finite-state archive from input FSTs.
#include <string>
#include <vector>
#include <fst/flags.h>
#include <fst/extensions/far/farscript.h>
#include <fst/extensions/far/getters.h>
#include <fstream>
DEFINE_string(key_prefix, "", "Prefix to append to keys");
DEFINE_string(key_suffix, "", "Suffix to append to keys");
DEFINE_int32(generate_keys, 0,
"Generate N digit numeric keys (def: use file basenames)");
DEFINE_string(far_type, "default",
"FAR file format type: one of: \"default\", "
"\"stlist\", \"sttable\"");
DEFINE_bool(file_list_input, false,
"Each input file contains a list of files to be processed");
int main(int argc, char **argv) {
namespace s = fst::script;
string usage = "Creates a finite-state archive from input FSTs.\n\n Usage:";
usage += argv[0];
usage += " [in1.fst [[in2.fst ...] out.far]]\n";
std::set_new_handler(FailedNewHandler);
SET_FLAGS(usage.c_str(), &argc, &argv, true);
s::ExpandArgs(argc, argv, &argc, &argv);
std::vector<string> in_fnames;
if (FLAGS_file_list_input) {
for (int i = 1; i < argc - 1; ++i) {
std::ifstream istrm(argv[i]);
string str;
while (getline(istrm, str)) in_fnames.push_back(str);
}
} else {
for (int i = 1; i < argc - 1; ++i)
in_fnames.push_back(argv[i]);
}
if (in_fnames.empty())
in_fnames.push_back(argc == 2 && strcmp(argv[1], "-") != 0 ? argv[1] : "");
string out_fname =
argc > 2 && strcmp(argv[argc - 1], "-") != 0 ? argv[argc - 1] : "";
const auto arc_type = s::LoadArcTypeFromFst(in_fnames[0]);
if (arc_type.empty()) return 1;
const auto far_type = s::GetFarType(FLAGS_far_type);
s::FarCreate(in_fnames, out_fname, arc_type, FLAGS_generate_keys, far_type,
FLAGS_key_prefix, FLAGS_key_suffix);
return 0;
}
| 0 |
coqui_public_repos/TTS | coqui_public_repos/TTS/recipes/README.md | # 🐸💬 TTS Training Recipes
TTS recipes intended to host scripts running all the necessary steps to train a TTS model on a particular dataset.
For each dataset, you need to download the dataset once. Then you run the training for the model you want.
Run each script from the root TTS folder as follows.
```console
$ sh ./recipes/<dataset>/download_<dataset>.sh
$ python recipes/<dataset>/<model_name>/train.py
```
For some datasets you might need to resample the audio files. For example, VCTK dataset can be resampled to 22050Hz as follows.
```console
python TTS/bin/resample.py --input_dir recipes/vctk/VCTK/wav48_silence_trimmed --output_sr 22050 --output_dir recipes/vctk/VCTK/wav48_silence_trimmed --n_jobs 8 --file_ext flac
```
If you train a new model using TTS, feel free to share your training to expand the list of recipes.
You can also open a new discussion and share your progress with the 🐸 community. | 0 |
coqui_public_repos/inference-engine/third_party | coqui_public_repos/inference-engine/third_party/tensorflow/types.h | /* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PLATFORM_TYPES_H_
#define TENSORFLOW_CORE_PLATFORM_TYPES_H_
#include <string>
#include "platform.h"
// Include appropriate platform-dependent implementations
#if defined(PLATFORM_GOOGLE) || defined(GOOGLE_INTEGRAL_TYPES)
#include "integral_types.h"
#elif defined(PLATFORM_POSIX) || defined(PLATFORM_POSIX_ANDROID) || \
defined(PLATFORM_GOOGLE_ANDROID) || defined(PLATFORM_POSIX_IOS) || \
defined(PLATFORM_GOOGLE_IOS) || defined(PLATFORM_WINDOWS)
#include "integral_types.h"
#else
#error Define the appropriate PLATFORM_<foo> macro for this platform
#endif
namespace tensorflow {
// Alias tensorflow::string to std::string.
using std::string;
static const uint8 kuint8max = static_cast<uint8>(0xFF);
static const uint16 kuint16max = static_cast<uint16>(0xFFFF);
static const uint32 kuint32max = static_cast<uint32>(0xFFFFFFFF);
static const uint64 kuint64max = static_cast<uint64>(0xFFFFFFFFFFFFFFFFull);
static const int8 kint8min = static_cast<int8>(~0x7F);
static const int8 kint8max = static_cast<int8>(0x7F);
static const int16 kint16min = static_cast<int16>(~0x7FFF);
static const int16 kint16max = static_cast<int16>(0x7FFF);
static const int32 kint32min = static_cast<int32>(~0x7FFFFFFF);
static const int32 kint32max = static_cast<int32>(0x7FFFFFFF);
static const int64 kint64min = static_cast<int64>(~0x7FFFFFFFFFFFFFFFll);
static const int64 kint64max = static_cast<int64>(0x7FFFFFFFFFFFFFFFll);
// A typedef for a uint64 used as a short fingerprint.
typedef uint64 Fprint;
} // namespace tensorflow
// Alias namespace ::stream_executor as ::tensorflow::se.
namespace stream_executor {}
namespace tensorflow {
namespace se = ::stream_executor;
} // namespace tensorflow
#if defined(PLATFORM_WINDOWS)
#include <cstddef>
typedef std::ptrdiff_t ssize_t;
#endif
#endif // TENSORFLOW_CORE_PLATFORM_TYPES_H_
| 0 |
coqui_public_repos/STT-examples | coqui_public_repos/STT-examples/electron/test.sh | #!/bin/bash
set -xe
THIS=$(dirname "$0")
OS=$(uname)
pushd ${THIS}
source ../tests.sh
if [ "${OS}" = "Linux" ]; then
export DISPLAY=':99.0'
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
xvfb_process=$!
fi
npm install $(get_npm_package_url)
npm install
npm run rebuild
if [ -f "${THIS}/node_modules/electron/dist/chrome-sandbox" ]; then
export ELECTRON_DISABLE_SANDBOX=1
fi;
ln -s $HOME/STT/models models
ln -s ~/STT/audio ./public/
export CI=true
npm run dev-test
if [ "${OS}" = "Linux" ]; then
sleep 1
kill -9 ${xvfb_process} || true
fi
popd
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/taskcluster/tf_win-amd64-cpu-opt.yml | build:
template_file: generic_tc_caching-win-opt-base.tyml
cache:
artifact_url: ${system.tensorflow.win_amd64_cpu.url}
artifact_namespace: ${system.tensorflow.win_amd64_cpu.namespace}
system_config:
>
${tensorflow.packages_win.pacman} && ${tensorflow.packages_win.msys64}
scripts:
setup: "taskcluster/tf_tc-setup.sh"
build: "taskcluster/tf_tc-build.sh --windows-cpu"
package: "taskcluster/tf_tc-package.sh"
maxRunTime: 14400
metadata:
name: "TensorFlow Windows AMD64 CPU"
description: "Building TensorFlow for Windows AMD64, CPU only, optimized version"
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions/linear/linear-fst-data-builder.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_EXTENSIONS_LINEAR_LINEAR_FST_DATA_BUILDER_H_
#define FST_EXTENSIONS_LINEAR_LINEAR_FST_DATA_BUILDER_H_
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#include <fst/compat.h>
#include <fst/log.h>
#include <fst/fst.h>
#include <fst/symbol-table.h>
#include <fst/util.h>
#include <fst/extensions/linear/linear-fst-data.h>
namespace fst {
// Forward declaration
template <class A>
class FeatureGroupBuilder;
// For logging purposes
inline string TranslateLabel(int64_t label, const SymbolTable *syms);
template <class Iterator>
string JoinLabels(Iterator begin, Iterator end, const SymbolTable *syms);
template <class Label>
string JoinLabels(const std::vector<Label> &labels, const SymbolTable *syms);
// Guesses the appropriate boundary label (start- or end-of-sentence)
// for all labels equal to `boundary` and modifies the `sequence`
// in-place. Returns the number of positions that are still uncertain.
template <class A>
typename A::Label GuessStartOrEnd(std::vector<typename A::Label> *sequence,
typename A::Label boundary);
// Builds a `LinearFstData` object by adding words and feature
// weights. A few conventions:
//
// - Input labels forms a dense non-empty range from 1 to `MaxInputLabel()`.
// - Feature labels, output labels are > 0.
// - Being a discriminative linear model, it only makes sense to use tropical
// semirings.
template <class A>
class LinearFstDataBuilder {
public:
typedef typename A::Label Label;
typedef typename A::Weight Weight;
// Constructs a builder with associated symbol tables for diagonstic
// output. Each of these symbol tables may also be nullptr.
explicit LinearFstDataBuilder(const SymbolTable *isyms = nullptr,
const SymbolTable *fsyms = nullptr,
const SymbolTable *osyms = nullptr)
: error_(false),
max_future_size_(0),
max_input_label_(1),
isyms_(isyms),
fsyms_(fsyms),
osyms_(osyms) {}
// Tests whether the builder has encountered any error. No operation
// is valid if the builder is already at error state. All other
// public methods should check this before any actual operations.
bool Error() const { return error_; }
// Adds a word and its feature labels to the vocabulary; this
// version allows the word to have any output label. Returns true
// iff the word is added.
//
// This may fail if the word is added twice or if the feature labels
// are non-positive.
bool AddWord(Label word, const std::vector<Label> &features);
// Adds a word and its feature labels to the vocabulary; this
// version puts constraint on possible output labels the word can
// have. `possible_output` must not be empty. Returns true iff the
// word is added.
//
// In addition to the reasons above in the two-parameter version,
// this may also fail if `possible_output` is empty or any output
// label in it is non-positive.
bool AddWord(Label word, const std::vector<Label> &word_features,
const std::vector<Label> &possible_output);
// Creates a new feature group with specified future size (size of
// the look-ahead window), returns the group id to be used for
// adding actual feature weights or a negative number when called at
// error state.
//
// This does not fail unless called at error state.
int AddGroup(size_t future_size);
// Adds an instance of feature weight to the specified feature
// group. If some weight has already been added with the same
// feature, the product of the old and new weights are
// stored. Returns true iff the weight is added. A weight is not
// added when the context has ill-formed context involving start-,
// end-of-sentence marks.
//
// For two features to be within the same group, it must satisfy
// that (1) they have the same future size; (2) the two either have
// disjoint context or one is the back-off context of the
// other. Furthermore, for all features in a single group, there
// must be one and only one other context (not necessarily an active
// feature) that the feature immediately backs off to (i.e. there is
// no other context that is the back-off of the first and backs off
// to the second).
//
// Consider for example features with zero look-ahead of the form
// (input, OUTPUT).
//
// - The following two features can be put in the same group because
// their context is disjoint: (a a a, A A), (b, B B);
//
// - The following two features can be put in the same group because
// one is the back-off context of the other: (a a a, A A), (a a, A
// A);
//
// - The following two features can NOT be put in the same group
// because there is overlap but neither is the other's back-off: (a
// a a, A), (a a, A A);
//
// - Finally, the following three features cannot be in a same group
// because the first one can immediately back off to either of the
// rest: (a a a, A A), (a a, A A), (a a a, A).
//
// The easiest way to satisfy the constraints is to create a feature
// group for each feature template. However, better feature grouping
// may help improve speed.
//
// This may fail if any of input or output labels are non-positive,
// or if any call to `FeatureGroupBuilder<>::AddWeight()` fails.
bool AddWeight(size_t group, const std::vector<Label> &input,
const std::vector<Label> &output, Weight weight);
// Returns a newly created `LinearFstData` object or nullptr in case
// of failure. The caller takes the ownership of the memory. No
// other methods shall be called after this --- this is enforced by
// putting the builder at error state, even when a
// `LinearFstData<>` object is successfully built.
//
// This may fail if the call to any `FeatureGroupBuilder<>::Dump()`
// fails.
LinearFstData<A> *Dump();
private:
bool error_;
CompactSet<Label, kNoLabel> all_output_labels_;
std::map<Label, std::set<Label>> word_output_map_, word_feat_map_;
std::map<Label, std::set<size_t>> feat_groups_;
std::vector<std::unique_ptr<FeatureGroupBuilder<A>>> groups_;
size_t max_future_size_;
Label max_input_label_;
const SymbolTable *isyms_, *fsyms_, *osyms_;
LinearFstDataBuilder(const LinearFstDataBuilder &) = delete;
LinearFstDataBuilder &operator=(const LinearFstDataBuilder &) = delete;
};
// Builds a LinearFstData tailored for a LinearClassifierFst. The
// major difference between an ordinary LinearFstData that works on
// taggers and a LinearFstData that works on classifiers is that
// feature groups are divided into sections by the prediction class
// label. For a prediction label `pred` and a logical group id
// `group`, the actual group id is `group * num_classes + pred -
// 1`.
//
// This layout saves us from recording output labels in each single
// FeatureGroup. Because there is no need for any delaying, stripping
// the output allows features with different shapes but using the same
// set of feature label mapping to reside in a single FeatureGroup.
template <class A>
class LinearClassifierFstDataBuilder {
public:
typedef typename A::Label Label;
typedef typename A::Weight Weight;
// Constructs a builder for a `num_classes`-class classifier,
// optinally with associated symbol tables for diagnostic
// output. The output labels (i.e. prediction) must be in the range
// of [1, num_classes].
explicit LinearClassifierFstDataBuilder(size_t num_classes,
const SymbolTable *isyms = nullptr,
const SymbolTable *fsyms = nullptr,
const SymbolTable *osyms = nullptr)
: error_(false),
num_classes_(num_classes),
num_groups_(0),
builder_(isyms, fsyms, osyms) {}
// Tests whether the builder has encountered any error. Similar to
// LinearFstDataBuilder<>::Error().
bool Error() const { return error_; }
// Same as LinearFstDataBuilder<>::AddWord().
bool AddWord(Label word, const std::vector<Label> &features);
// Adds a logical feature group. Similar to
// LinearFstDataBuilder<>::AddGroup(), with the exception that the
// returned group id is the logical group id. Also there is no need
// for "future" in a classifier.
int AddGroup();
// Adds an instance of feature weight to the specified logical
// feature group. Instead of a vector of output, only a single
// prediction is needed as the output.
//
// This may fail if `pred` is not in the range of [1, num_classes_].
bool AddWeight(size_t group, const std::vector<Label> &input, Label pred,
Weight weight);
// Returns a newly created `LinearFstData` object or nullptr in case of
// failure.
LinearFstData<A> *Dump();
private:
std::vector<Label> empty_;
bool error_;
size_t num_classes_, num_groups_;
LinearFstDataBuilder<A> builder_;
};
// Builds a single feature group. Usually used in
// `LinearFstDataBuilder::AddWeight()`. See that method for the
// constraints on grouping features.
template <class A>
class FeatureGroupBuilder {
public:
typedef typename A::Label Label;
typedef typename A::Weight Weight;
// Constructs a builder with the given future size. All features
// added to the group will have look-ahead windows of this size.
FeatureGroupBuilder(size_t future_size, const SymbolTable *fsyms,
const SymbolTable *osyms)
: error_(false), future_size_(future_size), fsyms_(fsyms), osyms_(osyms) {
// This edge is special; see doc of class `FeatureGroup` on the
// details.
start_ = trie_.Insert(trie_.Root(), InputOutputLabel(kNoLabel, kNoLabel));
}
// Tests whether the builder has encountered any error. No operation
// is valid if the builder is already at error state. All other
// public methods should check this before any actual operations.
bool Error() const { return error_; }
// Adds a feature weight with the given context. Returns true iff
// the weight is added. A weight is not added if it has ill-formed
// context involving start-, end-of-sentence marks.
//
// Note: `input` is the sequence of input
// features, instead of input labels themselves. `input` must be at
// least as long as `future_size`; `output` may be empty, but
// usually should be non-empty because an empty output context is
// useless in discriminative modelling. All labels in both `input`
// and `output` must be > 0 (this is checked in
// `LinearFstDataBuilder::AddWeight()`). See
// LinearFstDataBuilder<>::AddWeight for more details.
//
// This may fail if the input is smaller than the look-ahead window.
bool AddWeight(const std::vector<Label> &input,
const std::vector<Label> &output, Weight weight);
// Creates an actual FeatureGroup<> object. Connects back-off links;
// pre-accumulates weights from back-off features. Returns nullptr if
// there is any violation in unique immediate back-off
// constraints.
//
// Regardless of whether the call succeeds or not, the error flag is
// always set before this returns, to prevent repeated dumping.
//
// TODO(wuke): check overlapping top-level contexts (see
// `DumpOverlappingContext()` in tests).
FeatureGroup<A> *Dump(size_t max_future_size);
private:
typedef typename FeatureGroup<A>::InputOutputLabel InputOutputLabel;
typedef typename FeatureGroup<A>::InputOutputLabelHash InputOutputLabelHash;
typedef typename FeatureGroup<A>::WeightBackLink WeightBackLink;
// Nested trie topology uses more memory but we can traverse a
// node's children easily, which is required in `BuildBackLinks()`.
typedef NestedTrieTopology<InputOutputLabel, InputOutputLabelHash> Topology;
typedef MutableTrie<InputOutputLabel, WeightBackLink, Topology> Trie;
// Finds the first node with an arc with `label` following the
// back-off chain of `parent`. Returns the node index or
// `kNoTrieNodeId` when not found. The number of hops is stored in
// `hop` when it is not `nullptr`.
//
// This does not fail.
int FindFirstMatch(InputOutputLabel label, int parent, int *hop) const;
// Links each node to its immediate back-off. root is linked to -1.
//
// This may fail when the unique immediate back-off constraint is
// violated.
void BuildBackLinks();
// Traces back on the back-chain for each node to multiply the
// weights from back-offs to the node itself.
//
// This does not fail.
void PreAccumulateWeights();
// Reconstruct the path from trie root to given node for logging.
bool TrieDfs(const Topology &topology, int cur, int target,
std::vector<InputOutputLabel> *path) const;
string TriePath(int node, const Topology &topology) const;
bool error_;
size_t future_size_;
Trie trie_;
int start_;
const SymbolTable *fsyms_, *osyms_;
FeatureGroupBuilder(const FeatureGroupBuilder &) = delete;
FeatureGroupBuilder &operator=(const FeatureGroupBuilder &) = delete;
};
//
// Implementation of methods in `LinearFstDataBuilder`
//
template <class A>
bool LinearFstDataBuilder<A>::AddWord(Label word,
const std::vector<Label> &features) {
if (error_) {
FSTERROR() << "Calling LinearFstDataBuilder<>::AddWord() at error state";
return false;
}
if (word == LinearFstData<A>::kStartOfSentence ||
word == LinearFstData<A>::kEndOfSentence) {
LOG(WARNING) << "Ignored: adding boundary label: "
<< TranslateLabel(word, isyms_)
<< "(start-of-sentence=" << LinearFstData<A>::kStartOfSentence
<< ", end-of-sentence=" << LinearFstData<A>::kEndOfSentence
<< ")";
return false;
}
if (word <= 0) {
error_ = true;
FSTERROR() << "Word label must be > 0; got " << word;
return false;
}
if (word > max_input_label_) max_input_label_ = word;
// Make sure the word hasn't been added before
if (word_feat_map_.find(word) != word_feat_map_.end()) {
error_ = true;
FSTERROR() << "Input word " << TranslateLabel(word, isyms_)
<< " is added twice";
return false;
}
// Store features
std::set<Label> *feats = &word_feat_map_[word];
for (size_t i = 0; i < features.size(); ++i) {
Label feat = features[i];
if (feat <= 0) {
error_ = true;
FSTERROR() << "Feature label must be > 0; got " << feat;
return false;
}
feats->insert(feat);
}
return true;
}
template <class A>
bool LinearFstDataBuilder<A>::AddWord(
Label word, const std::vector<Label> &word_features,
const std::vector<Label> &possible_output) {
if (error_) {
FSTERROR() << "Calling LinearFstDataBuilder<>::AddWord() at error state";
return false;
}
if (!AddWord(word, word_features)) return false;
// Store possible output constraint
if (possible_output.empty()) {
error_ = true;
FSTERROR() << "Empty possible output constraint; "
<< "use the two-parameter version if no constraint is need.";
return false;
}
std::set<Label> *outputs = &word_output_map_[word];
for (size_t i = 0; i < possible_output.size(); ++i) {
Label output = possible_output[i];
if (output == LinearFstData<A>::kStartOfSentence ||
output == LinearFstData<A>::kEndOfSentence) {
LOG(WARNING) << "Ignored: word = " << TranslateLabel(word, isyms_)
<< ": adding boundary label as possible output: " << output
<< "(start-of-sentence="
<< LinearFstData<A>::kStartOfSentence
<< ", end-of-sentence=" << LinearFstData<A>::kEndOfSentence
<< ")";
continue;
}
if (output <= 0) {
error_ = true;
FSTERROR() << "Output label must be > 0; got " << output;
return false;
}
outputs->insert(output);
all_output_labels_.Insert(output);
}
return true;
}
template <class A>
inline int LinearFstDataBuilder<A>::AddGroup(size_t future_size) {
if (error_) {
FSTERROR() << "Calling LinearFstDataBuilder<>::AddGroup() at error state";
return -1;
}
size_t ret = groups_.size();
groups_.emplace_back(new FeatureGroupBuilder<A>(future_size, fsyms_, osyms_));
if (future_size > max_future_size_) max_future_size_ = future_size;
return ret;
}
template <class A>
bool LinearFstDataBuilder<A>::AddWeight(size_t group,
const std::vector<Label> &input,
const std::vector<Label> &output,
Weight weight) {
if (error_) {
FSTERROR() << "Calling LinearFstDataBuilder<>::AddWeight() at error state";
return false;
}
// Check well-formedness of boundary marks on the input.
{
bool start_in_middle = false, end_in_middle = false;
for (int i = 1; i < input.size(); ++i) {
if (input[i] == LinearFstData<A>::kStartOfSentence &&
input[i - 1] != LinearFstData<A>::kStartOfSentence)
start_in_middle = true;
if (input[i - 1] == LinearFstData<A>::kEndOfSentence &&
input[i] != LinearFstData<A>::kEndOfSentence)
end_in_middle = true;
}
if (start_in_middle) {
LOG(WARNING) << "Ignored: start-of-sentence in the middle of the input!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
if (end_in_middle) {
LOG(WARNING) << "Ignored: end-of-sentence in the middle of the input!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
}
// Check well-formedness of boundary marks on the output.
{
bool non_first_start = false, non_last_end = false;
for (int i = 1; i < output.size(); ++i) {
if (output[i] == LinearFstData<A>::kStartOfSentence)
non_first_start = true;
if (output[i - 1] == LinearFstData<A>::kEndOfSentence)
non_last_end = true;
}
if (non_first_start) {
LOG(WARNING) << "Ignored: start-of-sentence not appearing "
<< "as the first label in the output!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
if (non_last_end) {
LOG(WARNING) << "Ignored: end-of-sentence not appearing "
<< "as the last label in the output!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
}
for (size_t i = 0; i < input.size(); ++i) {
Label feat = input[i];
if (feat != LinearFstData<A>::kStartOfSentence &&
feat != LinearFstData<A>::kEndOfSentence && feat <= 0) {
error_ = true;
FSTERROR() << "Feature label must be > 0; got " << feat;
return false;
}
feat_groups_[feat].insert(group);
}
for (size_t i = 0; i < output.size(); ++i) {
Label label = output[i];
if (label != LinearFstData<A>::kStartOfSentence &&
label != LinearFstData<A>::kEndOfSentence && label <= 0) {
error_ = true;
FSTERROR() << "Output label must be > 0; got " << label;
return false;
}
if (label != LinearFstData<A>::kStartOfSentence &&
label != LinearFstData<A>::kEndOfSentence)
all_output_labels_.Insert(label);
}
// Everything looks good at this point (more checks on the way in
// the feature group). Add this feature weight.
bool added = groups_[group]->AddWeight(input, output, weight);
if (groups_[group]->Error()) {
error_ = true;
FSTERROR() << "FeatureGroupBuilder<>::AddWeight() failed";
return false;
}
return added;
}
template <class A>
LinearFstData<A> *LinearFstDataBuilder<A>::Dump() {
if (error_) {
FSTERROR() << "Calling LinearFstDataBuilder<>::Dump() at error state";
return nullptr;
}
std::unique_ptr<LinearFstData<A>> data(new LinearFstData<A>());
data->max_future_size_ = max_future_size_;
data->max_input_label_ = max_input_label_;
// Feature groups; free builders after it's dumped.
data->groups_.resize(groups_.size());
for (int group = 0; group != groups_.size(); ++group) {
FeatureGroup<A> *new_group = groups_[group]->Dump(max_future_size_);
if (new_group == nullptr) {
error_ = true;
FSTERROR() << "Error in dumping group " << group;
return nullptr;
}
data->groups_[group].reset(new_group);
groups_[group].reset();
VLOG(1) << "Group " << group << ": " << new_group->Stats();
}
// Per-group feature mapping
data->group_feat_map_.Init(data->NumGroups(), max_input_label_ + 1);
for (Label word = 1; word <= max_input_label_; ++word) {
typename std::map<Label, std::set<Label>>::const_iterator it =
word_feat_map_.find(word);
if (it == word_feat_map_.end()) continue;
for (typename std::set<Label>::const_iterator oit = it->second.begin();
oit != it->second.end(); ++oit) {
Label feat = *oit;
typename std::map<Label, std::set<size_t>>::const_iterator jt =
feat_groups_.find(feat);
if (jt == feat_groups_.end()) continue;
for (std::set<size_t>::const_iterator git = jt->second.begin();
git != jt->second.end(); ++git) {
size_t group_id = *git;
if (!data->group_feat_map_.Set(group_id, word, feat)) {
error_ = true;
return nullptr;
}
}
}
}
// Possible output labels
{
std::vector<typename LinearFstData<A>::InputAttribute> *input_attribs =
&data->input_attribs_;
std::vector<Label> *output_pool = &data->output_pool_;
input_attribs->resize(max_input_label_ + 1);
for (Label word = 0; word <= max_input_label_; ++word) {
typename std::map<Label, std::set<Label>>::const_iterator it =
word_output_map_.find(word);
if (it == word_output_map_.end()) {
(*input_attribs)[word].output_begin = 0;
(*input_attribs)[word].output_length = 0;
} else {
(*input_attribs)[word].output_begin = output_pool->size();
(*input_attribs)[word].output_length = it->second.size();
for (typename std::set<Label>::const_iterator oit = it->second.begin();
oit != it->second.end(); ++oit) {
Label olabel = *oit;
output_pool->push_back(olabel);
}
}
}
}
for (typename CompactSet<Label, kNoLabel>::const_iterator it =
all_output_labels_.Begin();
it != all_output_labels_.End(); ++it)
data->output_set_.push_back(*it);
error_ = true; // prevent future calls on this object
return data.release();
}
//
// Implementation of methods in `LinearClassifierFstDataBuilder`
//
template <class A>
inline bool LinearClassifierFstDataBuilder<A>::AddWord(
Label word, const std::vector<Label> &features) {
if (error_) {
FSTERROR() << "Calling LinearClassifierFstDataBuilder<>::AddWord() at "
"error state";
return false;
}
bool added = builder_.AddWord(word, features);
if (builder_.Error()) error_ = true;
return added;
}
template <class A>
inline int LinearClassifierFstDataBuilder<A>::AddGroup() {
if (error_) {
FSTERROR() << "Calling LinearClassifierFstDataBuilder<>::AddGroup() at "
"error state";
return -1;
}
for (int i = 0; i < num_classes_; ++i) builder_.AddGroup(0);
if (builder_.Error()) {
error_ = true;
return -1;
}
return num_groups_++;
}
template <class A>
inline bool LinearClassifierFstDataBuilder<A>::AddWeight(
size_t group, const std::vector<Label> &input, Label pred, Weight weight) {
if (error_) {
FSTERROR() << "Calling LinearClassifierFstDataBuilder<>::AddWeight() at "
"error state";
return false;
}
if (pred <= 0 || pred > num_classes_) {
FSTERROR() << "Out-of-range prediction label: " << pred
<< " (num classes = " << num_classes_ << ")";
error_ = true;
return false;
}
size_t real_group = group * num_classes_ + pred - 1;
bool added = builder_.AddWeight(real_group, input, empty_, weight);
if (builder_.Error()) error_ = true;
return added;
}
template <class A>
inline LinearFstData<A> *LinearClassifierFstDataBuilder<A>::Dump() {
if (error_) {
FSTERROR()
<< "Calling LinearClassifierFstDataBuilder<>::Dump() at error state";
return nullptr;
}
LinearFstData<A> *data = builder_.Dump();
error_ = true;
return data;
}
//
// Implementation of methods in `FeatureGroupBuilder`
//
template <class A>
bool FeatureGroupBuilder<A>::AddWeight(const std::vector<Label> &input,
const std::vector<Label> &output,
Weight weight) {
if (error_) {
FSTERROR() << "Calling FeatureGroupBuilder<>::AddWeight() at error state";
return false;
}
// `LinearFstDataBuilder<>::AddWeight()` ensures prefix/suffix
// properties for us. We can directly count.
int num_input_start = 0;
while (num_input_start < input.size() &&
input[num_input_start] == LinearFstData<A>::kStartOfSentence)
++num_input_start;
int num_output_start = 0;
while (num_output_start < output.size() &&
output[num_output_start] == LinearFstData<A>::kStartOfSentence)
++num_output_start;
int num_input_end = 0;
for (int i = input.size() - 1;
i >= 0 && input[i] == LinearFstData<A>::kEndOfSentence; --i)
++num_input_end;
int num_output_end = 0;
for (int i = output.size() - 1;
i >= 0 && output[i] == LinearFstData<A>::kEndOfSentence; --i)
++num_output_end;
DCHECK_LE(num_output_end, 1);
if (input.size() - num_input_start < future_size_) {
LOG(WARNING) << "Ignored: start-of-sentence in the future!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, fsyms_);
return false;
}
if (num_input_start > 0 &&
input.size() - future_size_ - num_input_start <
output.size() - num_output_start) {
LOG(WARNING) << "Ignored: matching start-of-sentence with actual output!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
if (num_output_start > 0 &&
input.size() - future_size_ - num_input_start >
output.size() - num_output_start) {
LOG(WARNING) << "Ignored: matching start-of-sentence with actual input!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
// The following two require `num_output_end` <= 1.
if (num_input_end > future_size_ && num_input_end - future_size_ != 1) {
LOG(WARNING) << "Ignored: matching end-of-sentence with actual output!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
if (num_output_end > 0 &&
((input.size() == future_size_ && future_size_ != num_input_end) ||
(input.size() > future_size_ &&
num_input_end != future_size_ + num_output_end))) {
LOG(WARNING) << "Ignored: matching end-of-sentence with actual input!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
// Check if the context has no other labels than boundary marks
// (such features are useless).
if (num_input_start + num_input_end == input.size() &&
num_output_start + num_output_end == output.size()) {
LOG(WARNING)
<< "Ignored: feature context consisting of only boundary marks!";
LOG(WARNING) << "\tInput: " << JoinLabels(input, fsyms_);
LOG(WARNING) << "\tOutput: " << JoinLabels(output, osyms_);
return false;
}
// Start point for insertion in the trie. Insert at `start_` iff the
// beginning of the context is non-consumed start-of-sentence.
int cur = (num_input_start == 0 && num_output_start <= future_size_)
? trie_.Root()
: start_;
// Skip all input start-of-sentence marks
size_t ipos = num_input_start;
// Skip to keep at most `future_size_` start-of-sentence marks
size_t opos =
num_output_start <= future_size_ ? 0 : num_output_start - future_size_;
// Skip `num_output_end` end-of-sentence marks on both input and output
size_t iend = !input.empty() ? input.size() - num_output_end : 0,
oend = output.size() - num_output_end;
// Further, when output is empty, keep at most `future_size_`
// end-of-sentence marks on input.
if (output.empty() && num_input_end > future_size_)
iend = input.size() - num_input_end + future_size_;
// Actual feature context is (input[ipos:iend], output[opos:oend]).
// Pad `kNoLabel` as don't cares on the shorter of actual `input`
// and `output`.
const size_t effective_input_size = iend - ipos,
effective_output_size = oend - opos;
if (effective_input_size > effective_output_size) {
for (size_t pad = effective_input_size - effective_output_size; pad != 0;
--pad, ++ipos)
cur = trie_.Insert(cur, InputOutputLabel(input[ipos], kNoLabel));
} else if (effective_input_size < effective_output_size) {
for (size_t pad = effective_output_size - effective_input_size; pad != 0;
--pad, ++opos)
cur = trie_.Insert(cur, InputOutputLabel(kNoLabel, output[opos]));
}
CHECK_EQ(iend - ipos, oend - opos);
for (; ipos != iend; ++ipos, ++opos)
cur = trie_.Insert(cur, InputOutputLabel(input[ipos], output[opos]));
// We only need to attach final weight when there is an output
// end-of-sentence. When there is only end-of-sentence on the input,
// they are all consumed as the end-of-sentence paddings from
// `LinearFstImpl<>::ShiftBuffer()`. `LinearFstImpl<>::Expand()`
// and `LinearFstImpl<>::MatchInput()` ensures no other
// transition takes place after consuming the padding.
if (num_output_end > 0 || (output.empty() && num_input_end > future_size_))
trie_[cur].final_weight = Times(trie_[cur].final_weight, weight);
else
trie_[cur].weight = Times(trie_[cur].weight, weight);
return true;
}
template <class A>
FeatureGroup<A> *FeatureGroupBuilder<A>::Dump(size_t max_future_size) {
if (error_) {
FSTERROR() << "Calling FeatureGroupBuilder<>::PreAccumulateWeights() "
<< "at error state";
return nullptr;
}
if (max_future_size < future_size_) {
error_ = true;
FSTERROR() << "max_future_size (= " << max_future_size
<< ") is smaller the builder's future_size (= " << future_size_
<< ")";
return nullptr;
}
BuildBackLinks();
if (error_) return nullptr;
PreAccumulateWeights(); // does not fail
FeatureGroup<A> *ret =
new FeatureGroup<A>(max_future_size - future_size_, start_);
// Walk around the trie to compute next states
ret->next_state_.resize(trie_.NumNodes());
const Topology &topology = trie_.TrieTopology();
for (int i = 0; i < topology.NumNodes(); ++i) {
int next = i;
while (next != topology.Root() && topology.ChildrenOf(next).empty() &&
trie_[next].final_weight ==
trie_[trie_[next].back_link].final_weight)
next = trie_[next].back_link;
ret->next_state_[i] = next;
}
// Copy the trie
typename FeatureGroup<A>::Trie store_trie(trie_);
ret->trie_.swap(store_trie);
// Put the builder at error state to prevent repeated call of `Dump()`.
error_ = true;
return ret;
}
template <class A>
int FeatureGroupBuilder<A>::FindFirstMatch(InputOutputLabel label, int parent,
int *hop) const {
int hop_count = 0;
int ret = kNoTrieNodeId;
for (; parent >= 0; parent = trie_[parent].back_link, ++hop_count) {
int next = trie_.Find(parent, label);
if (next != kNoTrieNodeId) {
ret = next;
break;
}
}
if (hop != nullptr) *hop = hop_count;
return ret;
}
template <class A>
void FeatureGroupBuilder<A>::BuildBackLinks() {
// Breadth first search from the root. In the case where we only
// have the input label, the immedate back-off is simply the longest
// suffix of the current node that is also in the trie. For a node
// reached from its parent with label L, we can simply walk through
// the parent's back-off chain to find the first state with an arc
// of the same label L. The uniqueness is always
// guanranteed. However, in the case with both input and output
// labels, it is possible to back off by removing first labels from
// either side, which in general causes non-uniqueness.
const Topology &topology = trie_.TrieTopology();
std::queue<int> q; // all enqueued or visited nodes have known links
// Note: nodes have back link initialized to -1 in their
// constructor.
q.push(trie_.Root());
while (!error_ && !q.empty()) {
int parent = q.front();
q.pop();
// Find links for every child
const typename Topology::NextMap &children = topology.ChildrenOf(parent);
for (typename Topology::NextMap::const_iterator eit = children.begin();
eit != children.end(); ++eit) {
const std::pair<InputOutputLabel, int> &edge = *eit;
InputOutputLabel label = edge.first;
int child = edge.second;
if (label.input == kNoLabel || label.output == kNoLabel) {
// Label pairs from root to here all have one and only one
// `kNoLabel` on the same side; equivalent to the
// "longest-suffix" case.
trie_[child].back_link =
FindFirstMatch(label, trie_[parent].back_link, nullptr);
} else {
// Neither side is `kNoLabel` at this point, there are
// three possible ways to back-off: if the parent backs
// off to some context with only one side non-empty, the
// empty side may remain empty; or else an exact match of
// both sides is needed. Try to find all three possible
// backs and look for the closest one (in terms of hops
// along the parent's back-off chain).
int only_input_hop, only_output_hop, full_hop;
int only_input_link =
FindFirstMatch(InputOutputLabel(label.input, kNoLabel), parent,
&only_input_hop),
only_output_link =
FindFirstMatch(InputOutputLabel(kNoLabel, label.output), parent,
&only_output_hop),
full_link =
FindFirstMatch(label, trie_[parent].back_link, &full_hop);
if (only_input_link != -1 && only_output_link != -1) {
error_ = true;
FSTERROR() << "Branching back-off chain:\n"
<< "\tnode " << child << ": " << TriePath(child, topology)
<< "\n"
<< "\tcan back-off to node " << only_input_link << ": "
<< TriePath(only_input_link, topology) << "\n"
<< "\tcan back-off to node " << only_output_link << ": "
<< TriePath(only_output_link, topology);
return;
} else if (full_link != -1) {
++full_hop;
if (full_hop <= only_input_hop && full_hop <= only_output_hop) {
trie_[child].back_link = full_link;
} else {
error_ = true;
int problem_link = only_input_link != kNoTrieNodeId
? only_input_link
: only_output_link;
CHECK_NE(problem_link, kNoTrieNodeId);
FSTERROR() << "Branching back-off chain:\n"
<< "\tnode " << child << ": "
<< TriePath(child, topology) << "\n"
<< "\tcan back-off to node " << full_link << ": "
<< TriePath(full_link, topology) << "\n"
<< "tcan back-off to node " << problem_link << ": "
<< TriePath(problem_link, topology);
return;
}
} else {
trie_[child].back_link =
only_input_link != -1 ? only_input_link : only_output_link;
}
}
if (error_) break;
// Point to empty context (root) when no back-off can be found
if (trie_[child].back_link == -1) trie_[child].back_link = 0;
q.push(child);
}
}
}
template <class A>
void FeatureGroupBuilder<A>::PreAccumulateWeights() {
std::vector<bool> visited(trie_.NumNodes(), false);
visited[trie_.Root()] = true;
for (size_t i = 0; i != trie_.NumNodes(); ++i) {
std::stack<int> back_offs;
for (int j = i; !visited[j]; j = trie_[j].back_link) back_offs.push(j);
while (!back_offs.empty()) {
int j = back_offs.top();
back_offs.pop();
WeightBackLink &node = trie_[j];
node.weight = Times(node.weight, trie_[node.back_link].weight);
node.final_weight =
Times(node.final_weight, trie_[node.back_link].final_weight);
visited[j] = true;
}
}
}
template <class A>
bool FeatureGroupBuilder<A>::TrieDfs(
const Topology &topology, int cur, int target,
std::vector<InputOutputLabel> *path) const {
if (cur == target) return true;
const typename Topology::NextMap &children = topology.ChildrenOf(cur);
for (typename Topology::NextMap::const_iterator eit = children.begin();
eit != children.end(); ++eit) {
const std::pair<InputOutputLabel, int> &edge = *eit;
path->push_back(edge.first);
if (TrieDfs(topology, edge.second, target, path)) return true;
path->pop_back();
}
return false;
}
template <class A>
string FeatureGroupBuilder<A>::TriePath(int node,
const Topology &topology) const {
std::vector<InputOutputLabel> labels;
TrieDfs(topology, topology.Root(), node, &labels);
bool first = true;
std::ostringstream strm;
for (typename std::vector<InputOutputLabel>::const_iterator it =
labels.begin();
it != labels.end(); ++it) {
InputOutputLabel i = *it;
if (first)
first = false;
else
strm << ", ";
strm << "(" << TranslateLabel(i.input, fsyms_) << ", "
<< TranslateLabel(i.output, osyms_) << ")";
}
return strm.str();
}
inline string TranslateLabel(int64_t label, const SymbolTable *syms) {
string ret;
if (syms != nullptr) ret += syms->Find(label);
if (ret.empty()) {
std::ostringstream strm;
strm << '<' << label << '>';
ret = strm.str();
}
return ret;
}
template <class Iterator>
string JoinLabels(Iterator begin, Iterator end, const SymbolTable *syms) {
if (begin == end) return "<empty>";
std::ostringstream strm;
bool first = true;
for (Iterator it = begin; it != end; ++it) {
if (first)
first = false;
else
strm << '|';
strm << TranslateLabel(*it, syms);
}
return strm.str();
}
template <class Label>
string JoinLabels(const std::vector<Label> &labels, const SymbolTable *syms) {
return JoinLabels(labels.begin(), labels.end(), syms);
}
template <class A>
typename A::Label GuessStartOrEnd(std::vector<typename A::Label> *sequence,
typename A::Label boundary) {
const size_t length = sequence->size();
std::vector<bool> non_boundary_on_left(length, false),
non_boundary_on_right(length, false);
for (size_t i = 1; i < length; ++i) {
non_boundary_on_left[i] =
non_boundary_on_left[i - 1] || (*sequence)[i - 1] != boundary;
non_boundary_on_right[length - 1 - i] = non_boundary_on_right[length - i] ||
(*sequence)[length - i] != boundary;
}
int unresolved = 0;
for (size_t i = 0; i < length; ++i) {
if ((*sequence)[i] != boundary) continue;
const bool left = non_boundary_on_left[i], right = non_boundary_on_right[i];
if (left && right) {
// Boundary in the middle
LOG(WARNING) << "Boundary label in the middle of the sequence! position: "
<< i << "; boundary: " << boundary
<< "; sequence: " << JoinLabels(*sequence, nullptr);
LOG(WARNING)
<< "This is an invalid sequence anyway so I will set it to start.";
(*sequence)[i] = LinearFstData<A>::kStartOfSentence;
} else if (left && !right) {
// Can only be end
(*sequence)[i] = LinearFstData<A>::kEndOfSentence;
} else if (!left && right) {
// Can only be start
(*sequence)[i] = LinearFstData<A>::kStartOfSentence;
} else {
// !left && !right; can't really tell
++unresolved;
}
}
return unresolved;
}
} // namespace fst
#endif // FST_EXTENSIONS_LINEAR_LINEAR_FST_DATA_BUILDER_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.9-win/src/include/fst/script/verify.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_SCRIPT_VERIFY_H_
#define FST_SCRIPT_VERIFY_H_
#include <fst/verify.h>
#include <fst/script/arg-packs.h>
#include <fst/script/fst-class.h>
namespace fst {
namespace script {
using VerifyArgs = WithReturnValue<bool, const FstClass &>;
template <class Arc>
void Verify(VerifyArgs *args) {
const Fst<Arc> &fst = *(args->args.GetFst<Arc>());
args->retval = Verify(fst);
}
bool Verify(const FstClass &fst);
} // namespace script
} // namespace fst
#endif // FST_SCRIPT_VERIFY_H_
| 0 |
coqui_public_repos/TTS/tests | coqui_public_repos/TTS/tests/vocoder_tests/test_hifigan_train.py | import glob
import os
import shutil
from tests import get_device_id, get_tests_output_path, run_cli
from TTS.vocoder.configs import HifiganConfig
config_path = os.path.join(get_tests_output_path(), "test_vocoder_config.json")
output_path = os.path.join(get_tests_output_path(), "train_outputs")
config = HifiganConfig(
batch_size=8,
eval_batch_size=8,
num_loader_workers=0,
num_eval_loader_workers=0,
run_eval=True,
test_delay_epochs=-1,
epochs=1,
seq_len=1024,
eval_split_size=1,
print_step=1,
print_eval=True,
data_path="tests/data/ljspeech",
output_path=output_path,
)
config.audio.do_trim_silence = True
config.audio.trim_db = 60
config.save_json(config_path)
# train the model for one epoch
command_train = f"CUDA_VISIBLE_DEVICES='{get_device_id()}' python TTS/bin/train_vocoder.py --config_path {config_path} "
run_cli(command_train)
# Find latest folder
continue_path = max(glob.glob(os.path.join(output_path, "*/")), key=os.path.getmtime)
# restore the model and continue training for one more epoch
command_train = (
f"CUDA_VISIBLE_DEVICES='{get_device_id()}' python TTS/bin/train_vocoder.py --continue_path {continue_path} "
)
run_cli(command_train)
shutil.rmtree(continue_path)
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/replace-util.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
//
// Utility classes for the recursive replacement of FSTs (RTNs).
#ifndef FST_REPLACE_UTIL_H_
#define FST_REPLACE_UTIL_H_
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <fst/log.h>
#include <fst/connect.h>
#include <fst/mutable-fst.h>
#include <fst/topsort.h>
#include <fst/vector-fst.h>
namespace fst {
// This specifies what labels to output on the call or return arc. Note that
// REPLACE_LABEL_INPUT and REPLACE_LABEL_OUTPUT will produce transducers when
// applied to acceptors.
enum ReplaceLabelType {
// Epsilon labels on both input and output.
REPLACE_LABEL_NEITHER = 1,
// Non-epsilon labels on input and epsilon on output.
REPLACE_LABEL_INPUT = 2,
// Epsilon on input and non-epsilon on output.
REPLACE_LABEL_OUTPUT = 3,
// Non-epsilon labels on both input and output.
REPLACE_LABEL_BOTH = 4
};
// By default ReplaceUtil will copy the input label of the replace arc.
// The call_label_type and return_label_type options specify how to manage
// the labels of the call arc and the return arc of the replace FST
struct ReplaceUtilOptions {
int64 root; // Root rule for expansion.
ReplaceLabelType call_label_type; // How to label call arc.
ReplaceLabelType return_label_type; // How to label return arc.
int64 return_label; // Label to put on return arc.
explicit ReplaceUtilOptions(
int64 root = kNoLabel,
ReplaceLabelType call_label_type = REPLACE_LABEL_INPUT,
ReplaceLabelType return_label_type = REPLACE_LABEL_NEITHER,
int64 return_label = 0)
: root(root),
call_label_type(call_label_type),
return_label_type(return_label_type),
return_label(return_label) {}
// For backwards compatibility.
ReplaceUtilOptions(int64 root, bool epsilon_replace_arc)
: ReplaceUtilOptions(root,
epsilon_replace_arc ? REPLACE_LABEL_NEITHER
: REPLACE_LABEL_INPUT) {}
};
// Every non-terminal on a path appears as the first label on that path in every
// FST associated with a given SCC of the replace dependency graph. This would
// be true if the SCC were formed from left-linear grammar rules.
constexpr uint8 kReplaceSCCLeftLinear = 0x01;
// Every non-terminal on a path appears as the final label on that path in every
// FST associated with a given SCC of the replace dependency graph. This would
// be true if the SCC were formed from right-linear grammar rules.
constexpr uint8 kReplaceSCCRightLinear = 0x02;
// The SCC in the replace dependency graph has more than one state or a
// self-loop.
constexpr uint8 kReplaceSCCNonTrivial = 0x04;
// Defined in replace.h.
template <class Arc>
void Replace(
const std::vector<std::pair<typename Arc::Label, const Fst<Arc> *>> &,
MutableFst<Arc> *, const ReplaceUtilOptions &);
// Utility class for the recursive replacement of FSTs (RTNs). The user provides
// a set of label/FST pairs at construction. These are used by methods for
// testing cyclic dependencies and connectedness and doing RTN connection and
// specific FST replacement by label or for various optimization properties. The
// modified results can be obtained with the GetFstPairs() or
// GetMutableFstPairs() methods.
template <class Arc>
class ReplaceUtil {
public:
using Label = typename Arc::Label;
using StateId = typename Arc::StateId;
using Weight = typename Arc::Weight;
using FstPair = std::pair<Label, const Fst<Arc> *>;
using MutableFstPair = std::pair<Label, MutableFst<Arc> *>;
using NonTerminalHash = std::unordered_map<Label, Label>;
// Constructs from mutable FSTs; FST ownership is given to ReplaceUtil.
ReplaceUtil(const std::vector<MutableFstPair> &fst_pairs,
const ReplaceUtilOptions &opts);
// Constructs from FSTs; FST ownership is retained by caller.
ReplaceUtil(const std::vector<FstPair> &fst_pairs,
const ReplaceUtilOptions &opts);
// Constructs from ReplaceFst internals; FST ownership is retained by caller.
ReplaceUtil(const std::vector<std::unique_ptr<const Fst<Arc>>> &fst_array,
const NonTerminalHash &nonterminal_hash,
const ReplaceUtilOptions &opts);
~ReplaceUtil() {
for (Label i = 0; i < fst_array_.size(); ++i) delete fst_array_[i];
}
// True if the non-terminal dependencies are cyclic. Cyclic dependencies will
// result in an unexpandable FST.
bool CyclicDependencies() const {
GetDependencies(false);
return depprops_ & kCyclic;
}
// Returns the strongly-connected component ID in the dependency graph of the
// replace FSTS.
StateId SCC(Label label) const {
GetDependencies(false);
const auto it = nonterminal_hash_.find(label);
if (it == nonterminal_hash_.end()) return kNoStateId;
return depscc_[it->second];
}
// Returns properties for the strongly-connected component in the dependency
// graph of the replace FSTs. If the SCC is kReplaceSCCLeftLinear or
// kReplaceSCCRightLinear, that SCC can be represented as finite-state despite
// any cyclic dependencies, but not by the usual replacement operation (see
// fst/extensions/pdt/replace.h).
uint8 SCCProperties(StateId scc_id) {
GetSCCProperties();
return depsccprops_[scc_id];
}
// Returns true if no useless FSTs, states or transitions are present in the
// RTN.
bool Connected() const {
GetDependencies(false);
uint64 props = kAccessible | kCoAccessible;
for (Label i = 0; i < fst_array_.size(); ++i) {
if (!fst_array_[i]) continue;
if (fst_array_[i]->Properties(props, true) != props || !depaccess_[i]) {
return false;
}
}
return true;
}
// Removes useless FSTs, states and transitions from the RTN.
void Connect();
// Replaces FSTs specified by labels, unless there are cyclic dependencies.
void ReplaceLabels(const std::vector<Label> &labels);
// Replaces FSTs that have at most nstates states, narcs arcs and nnonterm
// non-terminals (updating in reverse dependency order), unless there are
// cyclic dependencies.
void ReplaceBySize(size_t nstates, size_t narcs, size_t nnonterms);
// Replaces singleton FSTS, unless there are cyclic dependencies.
void ReplaceTrivial() { ReplaceBySize(2, 1, 1); }
// Replaces non-terminals that have at most ninstances instances (updating in
// dependency order), unless there are cyclic dependencies.
void ReplaceByInstances(size_t ninstances);
// Replaces non-terminals that have only one instance, unless there are cyclic
// dependencies.
void ReplaceUnique() { ReplaceByInstances(1); }
// Returns label/FST pairs, retaining FST ownership.
void GetFstPairs(std::vector<FstPair> *fst_pairs);
// Returns label/mutable FST pairs, giving FST ownership over to the caller.
void GetMutableFstPairs(std::vector<MutableFstPair> *mutable_fst_pairs);
private:
// FST statistics.
struct ReplaceStats {
StateId nstates; // Number of states.
StateId nfinal; // Number of final states.
size_t narcs; // Number of arcs.
Label nnonterms; // Number of non-terminals in FST.
size_t nref; // Number of non-terminal instances referring to this FST.
// Number of times that ith FST references this FST
std::map<Label, size_t> inref;
// Number of times that this FST references the ith FST
std::map<Label, size_t> outref;
ReplaceStats() : nstates(0), nfinal(0), narcs(0), nnonterms(0), nref(0) {}
};
// Checks that Mutable FSTs exists, creating them if necessary.
void CheckMutableFsts();
// Computes the dependency graph for the RTN, computing dependency statistics
// if stats is true.
void GetDependencies(bool stats) const;
void ClearDependencies() const {
depfst_.DeleteStates();
stats_.clear();
depprops_ = 0;
depsccprops_.clear();
have_stats_ = false;
}
// Gets topological order of dependencies, returning false with cyclic input.
bool GetTopOrder(const Fst<Arc> &fst, std::vector<Label> *toporder) const;
// Updates statistics to reflect the replacement of the jth FST.
void UpdateStats(Label j);
// Computes the properties for the strongly-connected component in the
// dependency graph of the replace FSTs.
void GetSCCProperties() const;
Label root_label_; // Root non-terminal.
Label root_fst_; // Root FST ID.
ReplaceLabelType call_label_type_; // See Replace().
ReplaceLabelType return_label_type_; // See Replace().
int64 return_label_; // See Replace().
std::vector<const Fst<Arc> *> fst_array_; // FST per ID.
std::vector<MutableFst<Arc> *> mutable_fst_array_; // Mutable FST per ID.
std::vector<Label> nonterminal_array_; // FST ID to non-terminal.
NonTerminalHash nonterminal_hash_; // Non-terminal to FST ID.
mutable VectorFst<Arc> depfst_; // FST ID dependencies.
mutable std::vector<StateId> depscc_; // FST SCC ID.
mutable std::vector<bool> depaccess_; // FST ID accessibility.
mutable uint64 depprops_; // Dependency FST props.
mutable bool have_stats_; // Have dependency statistics?
mutable std::vector<ReplaceStats> stats_; // Per-FST statistics.
mutable std::vector<uint8> depsccprops_; // SCC properties.
ReplaceUtil(const ReplaceUtil &) = delete;
ReplaceUtil &operator=(const ReplaceUtil &) = delete;
};
template <class Arc>
ReplaceUtil<Arc>::ReplaceUtil(const std::vector<MutableFstPair> &fst_pairs,
const ReplaceUtilOptions &opts)
: root_label_(opts.root),
call_label_type_(opts.call_label_type),
return_label_type_(opts.return_label_type),
return_label_(opts.return_label),
depprops_(0),
have_stats_(false) {
fst_array_.push_back(nullptr);
mutable_fst_array_.push_back(nullptr);
nonterminal_array_.push_back(kNoLabel);
for (const auto &fst_pair : fst_pairs) {
const auto label = fst_pair.first;
auto *fst = fst_pair.second;
nonterminal_hash_[label] = fst_array_.size();
nonterminal_array_.push_back(label);
fst_array_.push_back(fst);
mutable_fst_array_.push_back(fst);
}
root_fst_ = nonterminal_hash_[root_label_];
if (!root_fst_) {
FSTERROR() << "ReplaceUtil: No root FST for label: " << root_label_;
}
}
template <class Arc>
ReplaceUtil<Arc>::ReplaceUtil(const std::vector<FstPair> &fst_pairs,
const ReplaceUtilOptions &opts)
: root_label_(opts.root),
call_label_type_(opts.call_label_type),
return_label_type_(opts.return_label_type),
return_label_(opts.return_label),
depprops_(0),
have_stats_(false) {
fst_array_.push_back(nullptr);
nonterminal_array_.push_back(kNoLabel);
for (const auto &fst_pair : fst_pairs) {
const auto label = fst_pair.first;
const auto *fst = fst_pair.second;
nonterminal_hash_[label] = fst_array_.size();
nonterminal_array_.push_back(label);
fst_array_.push_back(fst->Copy());
}
root_fst_ = nonterminal_hash_[root_label_];
if (!root_fst_) {
FSTERROR() << "ReplaceUtil: No root FST for label: " << root_label_;
}
}
template <class Arc>
ReplaceUtil<Arc>::ReplaceUtil(
const std::vector<std::unique_ptr<const Fst<Arc>>> &fst_array,
const NonTerminalHash &nonterminal_hash, const ReplaceUtilOptions &opts)
: root_fst_(opts.root),
call_label_type_(opts.call_label_type),
return_label_type_(opts.return_label_type),
return_label_(opts.return_label),
nonterminal_array_(fst_array.size()),
nonterminal_hash_(nonterminal_hash),
depprops_(0),
have_stats_(false) {
fst_array_.push_back(nullptr);
for (size_t i = 1; i < fst_array.size(); ++i) {
fst_array_.push_back(fst_array[i]->Copy());
}
for (auto it = nonterminal_hash.begin(); it != nonterminal_hash.end(); ++it) {
nonterminal_array_[it->second] = it->first;
}
root_label_ = nonterminal_array_[root_fst_];
}
template <class Arc>
void ReplaceUtil<Arc>::GetDependencies(bool stats) const {
if (depfst_.NumStates() > 0) {
if (stats && !have_stats_) {
ClearDependencies();
} else {
return;
}
}
have_stats_ = stats;
if (have_stats_) stats_.reserve(fst_array_.size());
for (Label i = 0; i < fst_array_.size(); ++i) {
depfst_.AddState();
depfst_.SetFinal(i, Weight::One());
if (have_stats_) stats_.push_back(ReplaceStats());
}
depfst_.SetStart(root_fst_);
// An arc from each state (representing the FST) to the state representing the
// FST being replaced
for (Label i = 0; i < fst_array_.size(); ++i) {
const auto *ifst = fst_array_[i];
if (!ifst) continue;
for (StateIterator<Fst<Arc>> siter(*ifst); !siter.Done(); siter.Next()) {
const auto s = siter.Value();
if (have_stats_) {
++stats_[i].nstates;
if (ifst->Final(s) != Weight::Zero()) ++stats_[i].nfinal;
}
for (ArcIterator<Fst<Arc>> aiter(*ifst, s); !aiter.Done();
aiter.Next()) {
if (have_stats_) ++stats_[i].narcs;
const auto &arc = aiter.Value();
auto it = nonterminal_hash_.find(arc.olabel);
if (it != nonterminal_hash_.end()) {
const auto j = it->second;
depfst_.AddArc(i, Arc(arc.olabel, arc.olabel, Weight::One(), j));
if (have_stats_) {
++stats_[i].nnonterms;
++stats_[j].nref;
++stats_[j].inref[i];
++stats_[i].outref[j];
}
}
}
}
}
// Computes accessibility info.
SccVisitor<Arc> scc_visitor(&depscc_, &depaccess_, nullptr, &depprops_);
DfsVisit(depfst_, &scc_visitor);
}
template <class Arc>
void ReplaceUtil<Arc>::UpdateStats(Label j) {
if (!have_stats_) {
FSTERROR() << "ReplaceUtil::UpdateStats: Stats not available";
return;
}
if (j == root_fst_) return; // Can't replace root.
for (auto in = stats_[j].inref.begin(); in != stats_[j].inref.end(); ++in) {
const auto i = in->first;
const auto ni = in->second;
stats_[i].nstates += stats_[j].nstates * ni;
stats_[i].narcs += (stats_[j].narcs + 1) * ni;
stats_[i].nnonterms += (stats_[j].nnonterms - 1) * ni;
stats_[i].outref.erase(j);
for (auto out = stats_[j].outref.begin(); out != stats_[j].outref.end();
++out) {
const auto k = out->first;
const auto nk = out->second;
stats_[i].outref[k] += ni * nk;
}
}
for (auto out = stats_[j].outref.begin(); out != stats_[j].outref.end();
++out) {
const auto k = out->first;
const auto nk = out->second;
stats_[k].nref -= nk;
stats_[k].inref.erase(j);
for (auto in = stats_[j].inref.begin(); in != stats_[j].inref.end(); ++in) {
const auto i = in->first;
const auto ni = in->second;
stats_[k].inref[i] += ni * nk;
stats_[k].nref += ni * nk;
}
}
}
template <class Arc>
void ReplaceUtil<Arc>::CheckMutableFsts() {
if (mutable_fst_array_.empty()) {
for (Label i = 0; i < fst_array_.size(); ++i) {
if (!fst_array_[i]) {
mutable_fst_array_.push_back(nullptr);
} else {
mutable_fst_array_.push_back(new VectorFst<Arc>(*fst_array_[i]));
delete fst_array_[i];
fst_array_[i] = mutable_fst_array_[i];
}
}
}
}
template <class Arc>
void ReplaceUtil<Arc>::Connect() {
CheckMutableFsts();
static constexpr auto props = kAccessible | kCoAccessible;
for (auto *mutable_fst : mutable_fst_array_) {
if (!mutable_fst) continue;
if (mutable_fst->Properties(props, false) != props) {
fst::Connect(mutable_fst);
}
}
GetDependencies(false);
for (Label i = 0; i < mutable_fst_array_.size(); ++i) {
auto *fst = mutable_fst_array_[i];
if (fst && !depaccess_[i]) {
delete fst;
fst_array_[i] = nullptr;
mutable_fst_array_[i] = nullptr;
}
}
ClearDependencies();
}
template <class Arc>
bool ReplaceUtil<Arc>::GetTopOrder(const Fst<Arc> &fst,
std::vector<Label> *toporder) const {
// Finds topological order of dependencies.
std::vector<StateId> order;
bool acyclic = false;
TopOrderVisitor<Arc> top_order_visitor(&order, &acyclic);
DfsVisit(fst, &top_order_visitor);
if (!acyclic) {
LOG(WARNING) << "ReplaceUtil::GetTopOrder: Cyclical label dependencies";
return false;
}
toporder->resize(order.size());
for (Label i = 0; i < order.size(); ++i) (*toporder)[order[i]] = i;
return true;
}
template <class Arc>
void ReplaceUtil<Arc>::ReplaceLabels(const std::vector<Label> &labels) {
CheckMutableFsts();
std::unordered_set<Label> label_set;
for (const auto label : labels) {
// Can't replace root.
if (label != root_label_) label_set.insert(label);
}
// Finds FST dependencies restricted to the labels requested.
GetDependencies(false);
VectorFst<Arc> pfst(depfst_);
for (StateId i = 0; i < pfst.NumStates(); ++i) {
std::vector<Arc> arcs;
for (ArcIterator<VectorFst<Arc>> aiter(pfst, i); !aiter.Done();
aiter.Next()) {
const auto &arc = aiter.Value();
const auto label = nonterminal_array_[arc.nextstate];
if (label_set.count(label) > 0) arcs.push_back(arc);
}
pfst.DeleteArcs(i);
for (const auto &arc : arcs) pfst.AddArc(i, arc);
}
std::vector<Label> toporder;
if (!GetTopOrder(pfst, &toporder)) {
ClearDependencies();
return;
}
// Visits FSTs in reverse topological order of dependencies and performs
// replacements.
for (Label o = toporder.size() - 1; o >= 0; --o) {
std::vector<FstPair> fst_pairs;
auto s = toporder[o];
for (ArcIterator<VectorFst<Arc>> aiter(pfst, s); !aiter.Done();
aiter.Next()) {
const auto &arc = aiter.Value();
const auto label = nonterminal_array_[arc.nextstate];
const auto *fst = fst_array_[arc.nextstate];
fst_pairs.push_back(std::make_pair(label, fst));
}
if (fst_pairs.empty()) continue;
const auto label = nonterminal_array_[s];
const auto *fst = fst_array_[s];
fst_pairs.push_back(std::make_pair(label, fst));
const ReplaceUtilOptions opts(label, call_label_type_, return_label_type_,
return_label_);
Replace(fst_pairs, mutable_fst_array_[s], opts);
}
ClearDependencies();
}
template <class Arc>
void ReplaceUtil<Arc>::ReplaceBySize(size_t nstates, size_t narcs,
size_t nnonterms) {
std::vector<Label> labels;
GetDependencies(true);
std::vector<Label> toporder;
if (!GetTopOrder(depfst_, &toporder)) {
ClearDependencies();
return;
}
for (Label o = toporder.size() - 1; o >= 0; --o) {
const auto j = toporder[o];
if (stats_[j].nstates <= nstates && stats_[j].narcs <= narcs &&
stats_[j].nnonterms <= nnonterms) {
labels.push_back(nonterminal_array_[j]);
UpdateStats(j);
}
}
ReplaceLabels(labels);
}
template <class Arc>
void ReplaceUtil<Arc>::ReplaceByInstances(size_t ninstances) {
std::vector<Label> labels;
GetDependencies(true);
std::vector<Label> toporder;
if (!GetTopOrder(depfst_, &toporder)) {
ClearDependencies();
return;
}
for (Label o = 0; o < toporder.size(); ++o) {
const auto j = toporder[o];
if (stats_[j].nref <= ninstances) {
labels.push_back(nonterminal_array_[j]);
UpdateStats(j);
}
}
ReplaceLabels(labels);
}
template <class Arc>
void ReplaceUtil<Arc>::GetFstPairs(std::vector<FstPair> *fst_pairs) {
CheckMutableFsts();
fst_pairs->clear();
for (Label i = 0; i < fst_array_.size(); ++i) {
const auto label = nonterminal_array_[i];
const auto *fst = fst_array_[i];
if (!fst) continue;
fst_pairs->push_back(std::make_pair(label, fst));
}
}
template <class Arc>
void ReplaceUtil<Arc>::GetMutableFstPairs(
std::vector<MutableFstPair> *mutable_fst_pairs) {
CheckMutableFsts();
mutable_fst_pairs->clear();
for (Label i = 0; i < mutable_fst_array_.size(); ++i) {
const auto label = nonterminal_array_[i];
const auto *fst = mutable_fst_array_[i];
if (!fst) continue;
mutable_fst_pairs->push_back(std::make_pair(label, fst->Copy()));
}
}
template <class Arc>
void ReplaceUtil<Arc>::GetSCCProperties() const {
if (!depsccprops_.empty()) return;
GetDependencies(false);
if (depscc_.empty()) return;
for (StateId scc = 0; scc < depscc_.size(); ++scc) {
depsccprops_.push_back(kReplaceSCCLeftLinear | kReplaceSCCRightLinear);
}
if (!(depprops_ & kCyclic)) return; // No cyclic dependencies.
// Checks for self-loops in the dependency graph.
for (StateId scc = 0; scc < depscc_.size(); ++scc) {
for (ArcIterator<Fst<Arc> > aiter(depfst_, scc);
!aiter.Done(); aiter.Next()) {
const auto &arc = aiter.Value();
if (arc.nextstate == scc) { // SCC has a self loop.
depsccprops_[scc] |= kReplaceSCCNonTrivial;
}
}
}
std::vector<bool> depscc_visited(depscc_.size(), false);
for (Label i = 0; i < fst_array_.size(); ++i) {
const auto *fst = fst_array_[i];
if (!fst) continue;
const auto depscc = depscc_[i];
if (depscc_visited[depscc]) { // SCC has more than one state.
depsccprops_[depscc] |= kReplaceSCCNonTrivial;
}
depscc_visited[depscc] = true;
std::vector<StateId> fstscc; // SCCs of the current FST.
uint64 fstprops;
SccVisitor<Arc> scc_visitor(&fstscc, nullptr, nullptr, &fstprops);
DfsVisit(*fst, &scc_visitor);
for (StateIterator<Fst<Arc>> siter(*fst); !siter.Done(); siter.Next()) {
const auto s = siter.Value();
for (ArcIterator<Fst<Arc>> aiter(*fst, s); !aiter.Done(); aiter.Next()) {
const auto &arc = aiter.Value();
auto it = nonterminal_hash_.find(arc.olabel);
if (it == nonterminal_hash_.end() || depscc_[it->second] != depscc) {
continue; // Skips if a terminal or a non-terminal not in SCC.
}
const bool arc_in_cycle = fstscc[s] == fstscc[arc.nextstate];
// Left linear iff all non-terminals are initial.
if (s != fst->Start() || arc_in_cycle) {
depsccprops_[depscc] &= ~kReplaceSCCLeftLinear;
}
// Right linear iff all non-terminals are final.
if (fst->Final(arc.nextstate) == Weight::Zero() || arc_in_cycle) {
depsccprops_[depscc] &= ~kReplaceSCCRightLinear;
}
}
}
}
}
} // namespace fst
#endif // FST_REPLACE_UTIL_H_
| 0 |
coqui_public_repos/STT-examples/electron | coqui_public_repos/STT-examples/electron/public/index.html | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<link rel="stylesheet" href="fonts/stylesheet.css" type="text/css" charset="utf-8" />
<title>STT Electron Example</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions | coqui_public_repos/inference-engine/third_party/openfst-1.6.9-win/src/include/fst/extensions/far/compile-strings.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_EXTENSIONS_FAR_COMPILE_STRINGS_H_
#define FST_EXTENSIONS_FAR_COMPILE_STRINGS_H_
#ifndef _MSC_VER
#include <libgen.h>
#else
#include <fst/compat.h>
#endif
#include <fstream>
#include <istream>
#include <string>
#include <vector>
#include <fst/extensions/far/far.h>
#include <fstream>
#include <fst/string.h>
namespace fst {
// Constructs a reader that provides FSTs from a file (stream) either on a
// line-by-line basis or on a per-stream basis. Note that the freshly
// constructed reader is already set to the first input.
//
// Sample usage:
//
// for (StringReader<Arc> reader(...); !reader.Done(); reader.Next()) {
// auto *fst = reader.GetVectorFst();
// }
template <class Arc>
class StringReader {
public:
using Label = typename Arc::Label;
using Weight = typename Arc::Weight;
enum EntryType { LINE = 1, FILE = 2 };
StringReader(std::istream &istrm, const string &source, EntryType entry_type,
StringTokenType token_type, bool allow_negative_labels,
const SymbolTable *syms = nullptr,
Label unknown_label = kNoStateId)
: nline_(0),
istrm_(istrm),
source_(source),
entry_type_(entry_type),
token_type_(token_type),
symbols_(syms),
done_(false),
compiler_(token_type, syms, unknown_label, allow_negative_labels) {
Next(); // Initialize the reader to the first input.
}
bool Done() { return done_; }
void Next() {
VLOG(1) << "Processing source " << source_ << " at line " << nline_;
if (!istrm_) { // We're done if we have no more input.
done_ = true;
return;
}
if (entry_type_ == LINE) {
getline(istrm_, content_);
++nline_;
} else {
content_.clear();
string line;
while (getline(istrm_, line)) {
++nline_;
content_.append(line);
content_.append("\n");
}
}
if (!istrm_ && content_.empty()) // We're also done if we read off all the
done_ = true; // whitespace at the end of a file.
}
VectorFst<Arc> *GetVectorFst(bool keep_symbols = false) {
std::unique_ptr<VectorFst<Arc>> fst(new VectorFst<Arc>());
if (keep_symbols) {
fst->SetInputSymbols(symbols_);
fst->SetOutputSymbols(symbols_);
}
if (compiler_(content_, fst.get())) {
return fst.release();
} else {
return nullptr;
}
}
CompactStringFst<Arc> *GetCompactFst(bool keep_symbols = false) {
std::unique_ptr<CompactStringFst<Arc>> fst;
if (keep_symbols) {
VectorFst<Arc> tmp;
tmp.SetInputSymbols(symbols_);
tmp.SetOutputSymbols(symbols_);
fst.reset(new CompactStringFst<Arc>(tmp));
} else {
fst.reset(new CompactStringFst<Arc>());
}
if (compiler_(content_, fst.get())) {
return fst.release();
} else {
return nullptr;
}
}
private:
size_t nline_;
std::istream &istrm_;
string source_;
EntryType entry_type_;
StringTokenType token_type_;
const SymbolTable *symbols_;
bool done_;
StringCompiler<Arc> compiler_;
string content_; // The actual content of the input stream's next FST.
StringReader(const StringReader &) = delete;
StringReader &operator=(const StringReader &) = delete;
};
// Computes the minimal length required to encode each line number as a decimal
// number.
int KeySize(const char *filename);
template <class Arc>
void FarCompileStrings(const std::vector<string> &in_fnames,
const string &out_fname, const string &fst_type,
const FarType &far_type, int32_t generate_keys,
FarEntryType fet, FarTokenType tt,
const string &symbols_fname,
const string &unknown_symbol, bool keep_symbols,
bool initial_symbols, bool allow_negative_labels,
const string &key_prefix, const string &key_suffix) {
typename StringReader<Arc>::EntryType entry_type;
if (fet == FET_LINE) {
entry_type = StringReader<Arc>::LINE;
} else if (fet == FET_FILE) {
entry_type = StringReader<Arc>::FILE;
} else {
FSTERROR() << "FarCompileStrings: Unknown entry type";
return;
}
StringTokenType token_type;
if (tt == FTT_SYMBOL) {
token_type = StringTokenType::SYMBOL;
} else if (tt == FTT_BYTE) {
token_type = StringTokenType::BYTE;
} else if (tt == FTT_UTF8) {
token_type = StringTokenType::UTF8;
} else {
FSTERROR() << "FarCompileStrings: Unknown token type";
return;
}
bool compact;
if (fst_type.empty() || (fst_type == "vector")) {
compact = false;
} else if (fst_type == "compact") {
compact = true;
} else {
FSTERROR() << "FarCompileStrings: Unknown FST type: " << fst_type;
return;
}
std::unique_ptr<const SymbolTable> syms;
typename Arc::Label unknown_label = kNoLabel;
if (!symbols_fname.empty()) {
const SymbolTableTextOptions opts(allow_negative_labels);
syms.reset(SymbolTable::ReadText(symbols_fname, opts));
if (!syms) {
LOG(ERROR) << "FarCompileStrings: Error reading symbol table: "
<< symbols_fname;
return;
}
if (!unknown_symbol.empty()) {
unknown_label = syms->Find(unknown_symbol);
if (unknown_label == kNoLabel) {
FSTERROR() << "FarCompileStrings: Label \"" << unknown_label
<< "\" missing from symbol table: " << symbols_fname;
return;
}
}
}
std::unique_ptr<FarWriter<Arc>> far_writer(
FarWriter<Arc>::Create(out_fname, far_type));
if (!far_writer) return;
int n = 0;
for (const auto &in_fname : in_fnames) {
if (generate_keys == 0 && in_fname.empty()) {
FSTERROR() << "FarCompileStrings: Read from a file instead of stdin or"
<< " set the --generate_keys flags.";
return;
}
int key_size =
generate_keys ? generate_keys : (entry_type == StringReader<Arc>::FILE
? 1 : KeySize(in_fname.c_str()));
std::ifstream fstrm;
if (!in_fname.empty()) {
fstrm.open(in_fname);
if (!fstrm) {
FSTERROR() << "FarCompileStrings: Can't open file: " << in_fname;
return;
}
}
std::istream &istrm = fstrm.is_open() ? fstrm : std::cin;
bool keep_syms = keep_symbols;
for (StringReader<Arc> reader(
istrm, in_fname.empty() ? "stdin" : in_fname, entry_type,
token_type, allow_negative_labels, syms.get(), unknown_label);
!reader.Done(); reader.Next()) {
++n;
std::unique_ptr<const Fst<Arc>> fst;
if (compact) {
fst.reset(reader.GetCompactFst(keep_syms));
} else {
fst.reset(reader.GetVectorFst(keep_syms));
}
if (initial_symbols) keep_syms = false;
if (!fst) {
FSTERROR() << "FarCompileStrings: Compiling string number " << n
<< " in file " << in_fname << " failed with token_type = "
<< (tt == FTT_BYTE
? "byte"
: (tt == FTT_UTF8
? "utf8"
: (tt == FTT_SYMBOL ? "symbol" : "unknown")))
<< " and entry_type = "
<< (fet == FET_LINE
? "line"
: (fet == FET_FILE ? "file" : "unknown"));
return;
}
std::ostringstream keybuf;
keybuf.width(key_size);
keybuf.fill('0');
keybuf << n;
string key;
if (generate_keys > 0) {
key = keybuf.str();
} else {
auto *filename = new char[in_fname.size() + 1];
strcpy(filename, in_fname.c_str());
key = basename(filename);
if (entry_type != StringReader<Arc>::FILE) {
key += "-";
key += keybuf.str();
}
delete[] filename;
}
far_writer->Add(key_prefix + key + key_suffix, *fst);
}
if (generate_keys == 0) n = 0;
}
}
} // namespace fst
#endif // FST_EXTENSIONS_FAR_COMPILE_STRINGS_H_
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions/python/memory.pxd | # See www.openfst.org for extensive documentation on this weighted
# finite-state transducer library.
from libcpp.memory cimport shared_ptr
# This is mysteriously missing from libcpp.memory.
cdef extern from "<memory>" namespace "std" nogil:
shared_ptr[T] static_pointer_cast[T, U](const shared_ptr[U] &)
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions/compact/compact8_weighted_string-fst.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/fst.h>
#include <fst/compact-fst.h>
namespace fst {
static FstRegisterer<
CompactWeightedStringFst<StdArc, uint8>>
CompactWeightedStringFst_StdArc_uint8_registerer;
static FstRegisterer<
CompactWeightedStringFst<LogArc, uint8>>
CompactWeightedStringFst_LogArc_uint8_registerer;
} // namespace fst
| 0 |
coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions | coqui_public_repos/inference-engine/third_party/openfst-1.6.7/src/extensions/compact/compact16_unweighted_acceptor-fst.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/fst.h>
#include <fst/compact-fst.h>
namespace fst {
static FstRegisterer<
CompactUnweightedAcceptorFst<StdArc, uint16>>
CompactUnweightedAcceptorFst_StdArc_uint16_registerer;
static FstRegisterer<
CompactUnweightedAcceptorFst<LogArc, uint16>>
CompactUnweightedAcceptorFst_LogArc_uint16_registerer;
} // namespace fst
| 0 |
coqui_public_repos/STT-models/romanian/itml | coqui_public_repos/STT-models/romanian/itml/v0.1.1/LICENSE | GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions/pdt/getters.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/extensions/pdt/getters.h>
namespace fst {
namespace script {
bool GetPdtComposeFilter(const string &str, PdtComposeFilter *cf) {
if (str == "expand") {
*cf = EXPAND_FILTER;
} else if (str == "expand_paren") {
*cf = EXPAND_PAREN_FILTER;
} else if (str == "paren") {
*cf = PAREN_FILTER;
} else {
return false;
}
return true;
}
bool GetPdtParserType(const string &str, PdtParserType *pt) {
if (str == "left") {
*pt = PDT_LEFT_PARSER;
} else if (str == "left_sr") {
*pt = PDT_LEFT_SR_PARSER;
} else {
return false;
}
return true;
}
} // namespace script
} // namespace fst
| 0 |
coqui_public_repos | coqui_public_repos/open-bible-scripts/README.md | # Align [`Open.Bible`](https://open.bible/) data
|Language|Passing|Failing|Unknown|Notes|Aligned Sample|
|---------|------|-------|-------|----|-------|
|Yoruba|💚||||[Psalm 119](https://coqui-ai-public-data.s3.amazonaws.com/psalm-119-yoruba.tar.gz)|
|Ewe|💚||||[Psalm 119](https://coqui-ai-public-data.s3.amazonaws.com/ewe-psalm119-coqui-dec11.tar.gz)|
|Lingala|💚||||[Psalm 119](https://coqui-ai-public-data.s3.amazonaws.com/lingala-coqui-psalm119-dec16.tar.gz)|
|Asante Twi|💚|||||
|Akuapem Twi|💚|||||
|Chichewa|❤️🩹|||Passing with bad alignments|[Psalm 119](https://coqui-ai-public-data.s3.amazonaws.com/chichewa-coqui-PSA_119.tar.gz)|
|Hausa||💔||||
|Luo||💔||||
|Luganda||💔||||
|Kikuyu||💔||||
|Arabic|||❓|||
|Kurdi Sorani|||❓|||
|Polish|||❓|||
|Vietnamese|||❓|||
### Clone this repo
```
$ git clone https://github.com/coqui-ai/open-bible-scripts.git
```
## Alignment Approach 1: Use the Montreal Forced Aligner
The first alignment approach is to use MFA to align and train a new acoustic model from stratch.
### Dependencies
You need to install a couple things on your own:
[`gnu-parallel`](https://www.gnu.org/software/parallel/)
[`covo`](https://www.github.com/ftyers/commonvoice-utils)
### Start with the run script for pre-processing
Use the language name as defined in `open-bible-scripts/data/*.txt`. Use the language code as expected by [covo](https://www.github.com/ftyers/commonvoice-utils).
E.g., for Yoruba use `yoruba` and `yo`, for Ewe use `ewe` and `ee`, for Luganda `luganda` and `lg`, and so on.
```
$ cd open-bible-scripts
open-bible-scripts$ ./run-pre-alignment.sh yoruba yo
```
### Generate alignments with [`mfa train`](https://montreal-forced-aligner.readthedocs.io/en/latest/user_guide/workflows/train_acoustic_model.html)
```
$ docker run -it --mount "type=bind,src=/home/ubuntu/open-bible-scripts,dst=/mnt" mmcauliffe/montreal-forced-aligner
(base) root@d8095c794d5f:/# conda activate aligner
(aligner) root@d8095c794d5f:/# mfa train --clean --num_jobs `nproc` --temp_directory /mnt/yoruba/data/mfa-tmp-dir --config_path /mnt/MFA_CONFIG /mnt/yoruba/data /mnt/yoruba/dict.txt /mnt/yoruba/data/mfa-output &> /mnt/yoruba/data/LOG &
# At this point, alignment will take a while,
# so you might want to detach from the docker container
# with `Ctrl-P followed by Ctrl-Q`
```
### Finish with the run script for post-processing
Use the language name as defined in `open-bible-scripts/data/*.txt`.
E.g., for Yoruba use `yoruba`, for Ewe use `ewe`, for Luganda `luganda`, and so on.
```
$ cd open-bible-scripts
open-bible-scripts$ ./run-post-alignment.sh yoruba yo
```
## Alignment Approach 2: Use timing files from Biblica
This works for only Lingala, Akuapem Twi, and Asante Twi.
### Split using timing file
Install sox on your OS. See linux installation below
```bash
sudo apt-get install sox
sudo apt-get install libsox-fmt-mp3
sox --version
python3 -m venv venv
source venv/bin/activate
pip install -U pip
pip install pandas
```
Execute the `run-biblica-splits-*.sh` script from the root dir, for example with Lingala:
```bash
./run-biblica-splits-lingala.sh
```
| 0 |
coqui_public_repos/STT/native_client/kenlm | coqui_public_repos/STT/native_client/kenlm/lm/model.hh | #ifndef LM_MODEL_H
#define LM_MODEL_H
#include "bhiksha.hh"
#include "binary_format.hh"
#include "config.hh"
#include "facade.hh"
#include "quantize.hh"
#include "search_hashed.hh"
#include "search_trie.hh"
#include "state.hh"
#include "value.hh"
#include "vocab.hh"
#include "weights.hh"
#include "../util/murmur_hash.hh"
#include <algorithm>
#include <vector>
#include <cstring>
namespace util { class FilePiece; }
namespace lm {
namespace ngram {
namespace detail {
// Should return the same results as SRI.
// ModelFacade typedefs Vocabulary so we use VocabularyT to avoid naming conflicts.
template <class Search, class VocabularyT> class GenericModel : public base::ModelFacade<GenericModel<Search, VocabularyT>, State, VocabularyT> {
private:
typedef base::ModelFacade<GenericModel<Search, VocabularyT>, State, VocabularyT> P;
public:
// This is the model type returned by RecognizeBinary.
static const ModelType kModelType;
static const unsigned int kVersion = Search::kVersion;
/* Get the size of memory that will be mapped given ngram counts. This
* does not include small non-mapped control structures, such as this class
* itself.
*/
static uint64_t Size(const std::vector<uint64_t> &counts, const Config &config = Config());
/* Load the model from a file. It may be an ARPA or binary file. Binary
* files must have the format expected by this class or you'll get an
* exception. So TrieModel can only load ARPA or binary created by
* TrieModel. To classify binary files, call RecognizeBinary in
* lm/binary_format.hh.
*/
explicit GenericModel(const char *file, const Config &config = Config());
explicit GenericModel(const char *file_data, const uint64_t file_data_size, const Config &config = Config());
/* Score p(new_word | in_state) and incorporate new_word into out_state.
* Note that in_state and out_state must be different references:
* &in_state != &out_state.
*/
FullScoreReturn FullScore(const State &in_state, const WordIndex new_word, State &out_state) const;
/* Slower call without in_state. Try to remember state, but sometimes it
* would cost too much memory or your decoder isn't setup properly.
* To use this function, make an array of WordIndex containing the context
* vocabulary ids in reverse order. Then, pass the bounds of the array:
* [context_rbegin, context_rend). The new_word is not part of the context
* array unless you intend to repeat words.
*/
FullScoreReturn FullScoreForgotState(const WordIndex *context_rbegin, const WordIndex *context_rend, const WordIndex new_word, State &out_state) const;
/* Get the state for a context. Don't use this if you can avoid it. Use
* BeginSentenceState or NullContextState and extend from those. If
* you're only going to use this state to call FullScore once, use
* FullScoreForgotState.
* To use this function, make an array of WordIndex containing the context
* vocabulary ids in reverse order. Then, pass the bounds of the array:
* [context_rbegin, context_rend).
*/
void GetState(const WordIndex *context_rbegin, const WordIndex *context_rend, State &out_state) const;
/* More efficient version of FullScore where a partial n-gram has already
* been scored.
* NOTE: THE RETURNED .rest AND .prob ARE RELATIVE TO THE .rest RETURNED BEFORE.
*/
FullScoreReturn ExtendLeft(
// Additional context in reverse order. This will update add_rend to
const WordIndex *add_rbegin, const WordIndex *add_rend,
// Backoff weights to use.
const float *backoff_in,
// extend_left returned by a previous query.
uint64_t extend_pointer,
// Length of n-gram that the pointer corresponds to.
unsigned char extend_length,
// Where to write additional backoffs for [extend_length + 1, min(Order() - 1, return.ngram_length)]
float *backoff_out,
// Amount of additional content that should be considered by the next call.
unsigned char &next_use) const;
/* Return probabilities minus rest costs for an array of pointers. The
* first length should be the length of the n-gram to which pointers_begin
* points.
*/
float UnRest(const uint64_t *pointers_begin, const uint64_t *pointers_end, unsigned char first_length) const {
// Compiler should optimize this if away.
return Search::kDifferentRest ? InternalUnRest(pointers_begin, pointers_end, first_length) : 0.0;
}
uint64_t GetEndOfSearchOffset() const;
private:
FullScoreReturn ScoreExceptBackoff(const WordIndex *const context_rbegin, const WordIndex *const context_rend, const WordIndex new_word, State &out_state) const;
// Score bigrams and above. Do not include backoff.
void ResumeScore(const WordIndex *context_rbegin, const WordIndex *const context_rend, unsigned char starting_order_minus_2, typename Search::Node &node, float *backoff_out, unsigned char &next_use, FullScoreReturn &ret) const;
// Appears after Size in the cc file.
void SetupMemory(void *start, const std::vector<uint64_t> &counts, const Config &config);
void InitializeFromARPA(int fd, const char *file, const Config &config);
float InternalUnRest(const uint64_t *pointers_begin, const uint64_t *pointers_end, unsigned char first_length) const;
BinaryFormat backing_;
VocabularyT vocab_;
Search search_;
};
} // namespace detail
// Instead of typedef, inherit. This allows the Model etc to be forward declared.
// Oh the joys of C and C++.
#define LM_COMMA() ,
#define LM_NAME_MODEL(name, from)\
class name : public from {\
public:\
name(const char *file, const Config &config = Config()) : from(file, config) {}\
name(const char *file_data, size_t file_data_size, const Config &config = Config()) : from(file_data, file_data_size, config) {}\
};
LM_NAME_MODEL(ProbingModel, detail::GenericModel<detail::HashedSearch<BackoffValue> LM_COMMA() ProbingVocabulary>);
LM_NAME_MODEL(RestProbingModel, detail::GenericModel<detail::HashedSearch<RestValue> LM_COMMA() ProbingVocabulary>);
LM_NAME_MODEL(TrieModel, detail::GenericModel<trie::TrieSearch<DontQuantize LM_COMMA() trie::DontBhiksha> LM_COMMA() SortedVocabulary>);
LM_NAME_MODEL(ArrayTrieModel, detail::GenericModel<trie::TrieSearch<DontQuantize LM_COMMA() trie::ArrayBhiksha> LM_COMMA() SortedVocabulary>);
LM_NAME_MODEL(QuantTrieModel, detail::GenericModel<trie::TrieSearch<SeparatelyQuantize LM_COMMA() trie::DontBhiksha> LM_COMMA() SortedVocabulary>);
LM_NAME_MODEL(QuantArrayTrieModel, detail::GenericModel<trie::TrieSearch<SeparatelyQuantize LM_COMMA() trie::ArrayBhiksha> LM_COMMA() SortedVocabulary>);
// Default implementation. No real reason for it to be the default.
typedef ::lm::ngram::ProbingVocabulary Vocabulary;
typedef ProbingModel Model;
/* Autorecognize the file type, load, and return the virtual base class. Don't
* use the virtual base class if you can avoid it. Instead, use the above
* classes as template arguments to your own virtual feature function.*/
KENLM_EXPORT base::Model *LoadVirtual(const char *file_name, const Config &config = Config(), ModelType if_arpa = PROBING);
KENLM_EXPORT base::Model *LoadVirtual(const char *file_data, const uint64_t file_data_size, const Config &config = Config(), ModelType if_arpa = PROBING);
} // namespace ngram
} // namespace lm
#endif // LM_MODEL_H
| 0 |
coqui_public_repos/TTS/recipes/ljspeech | coqui_public_repos/TTS/recipes/ljspeech/tacotron2-DDC/train_tacotron_ddc.py | import os
from trainer import Trainer, TrainerArgs
from TTS.config.shared_configs import BaseAudioConfig
from TTS.tts.configs.shared_configs import BaseDatasetConfig
from TTS.tts.configs.tacotron2_config import Tacotron2Config
from TTS.tts.datasets import load_tts_samples
from TTS.tts.models.tacotron2 import Tacotron2
from TTS.tts.utils.text.tokenizer import TTSTokenizer
from TTS.utils.audio import AudioProcessor
# from TTS.tts.datasets.tokenizer import Tokenizer
output_path = os.path.dirname(os.path.abspath(__file__))
# init configs
dataset_config = BaseDatasetConfig(
formatter="ljspeech", meta_file_train="metadata.csv", path=os.path.join(output_path, "../LJSpeech-1.1/")
)
audio_config = BaseAudioConfig(
sample_rate=22050,
do_trim_silence=True,
trim_db=60.0,
signal_norm=False,
mel_fmin=0.0,
mel_fmax=8000,
spec_gain=1.0,
log_func="np.log",
ref_level_db=20,
preemphasis=0.0,
)
config = Tacotron2Config( # This is the config that is saved for the future use
audio=audio_config,
batch_size=64,
eval_batch_size=16,
num_loader_workers=4,
num_eval_loader_workers=4,
run_eval=True,
test_delay_epochs=-1,
r=6,
gradual_training=[[0, 6, 64], [10000, 4, 32], [50000, 3, 32], [100000, 2, 32]],
double_decoder_consistency=True,
epochs=1000,
text_cleaner="phoneme_cleaners",
use_phonemes=True,
phoneme_language="en-us",
phoneme_cache_path=os.path.join(output_path, "phoneme_cache"),
precompute_num_workers=8,
print_step=25,
print_eval=True,
mixed_precision=False,
output_path=output_path,
datasets=[dataset_config],
)
# init audio processor
ap = AudioProcessor(**config.audio.to_dict())
# INITIALIZE THE AUDIO PROCESSOR
# Audio processor is used for feature extraction and audio I/O.
# It mainly serves to the dataloader and the training loggers.
ap = AudioProcessor.init_from_config(config)
# INITIALIZE THE TOKENIZER
# Tokenizer is used to convert text to sequences of token IDs.
# If characters are not defined in the config, default characters are passed to the config
tokenizer, config = TTSTokenizer.init_from_config(config)
# LOAD DATA SAMPLES
# Each sample is a list of ```[text, audio_file_path, speaker_name]```
# You can define your custom sample loader returning the list of samples.
# Or define your custom formatter and pass it to the `load_tts_samples`.
# Check `TTS.tts.datasets.load_tts_samples` for more details.
train_samples, eval_samples = load_tts_samples(
dataset_config,
eval_split=True,
eval_split_max_size=config.eval_split_max_size,
eval_split_size=config.eval_split_size,
)
# INITIALIZE THE MODEL
# Models take a config object and a speaker manager as input
# Config defines the details of the model like the number of layers, the size of the embedding, etc.
# Speaker manager is used by multi-speaker models.
model = Tacotron2(config, ap, tokenizer, speaker_manager=None)
# init the trainer and 🚀
trainer = Trainer(
TrainerArgs(), config, output_path, model=model, train_samples=train_samples, eval_samples=eval_samples
)
trainer.fit()
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/taskcluster/android-x86_64-cpu-opt.yml | build:
template_file: linux-opt-base.tyml
dependencies:
- "swig-linux-amd64"
- "node-gyp-cache"
- "pyenv-linux-amd64"
- "tf_android-arm64-opt"
routes:
- "index.project.deepspeech.deepspeech.native_client.${event.head.branchortag}.android-x86_64"
- "index.project.deepspeech.deepspeech.native_client.${event.head.branchortag}.${event.head.sha}.android-x86_64"
- "index.project.deepspeech.deepspeech.native_client.android-x86_64.${event.head.sha}"
tensorflow: ${system.tensorflow.android_arm64.url}
scripts:
build: "taskcluster/android-build.sh x86_64"
package: "taskcluster/android-package.sh x86_64"
nc_asset_name: "native_client.x86_64.cpu.android.tar.xz"
workerType: "${docker.dsBuild}"
metadata:
name: "DeepSpeech Android x86_64"
description: "Building DeepSpeech for Android x86_64, optimized version"
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/include/fst/extensions/special/phi-fst.h | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#ifndef FST_EXTENSIONS_SPECIAL_PHI_FST_H_
#define FST_EXTENSIONS_SPECIAL_PHI_FST_H_
#include <memory>
#include <string>
#include <fst/const-fst.h>
#include <fst/matcher-fst.h>
#include <fst/matcher.h>
DECLARE_int64(phi_fst_phi_label);
DECLARE_bool(phi_fst_phi_loop);
DECLARE_string(phi_fst_rewrite_mode);
namespace fst {
namespace internal {
template <class Label>
class PhiFstMatcherData {
public:
PhiFstMatcherData(
Label phi_label = FLAGS_phi_fst_phi_label,
bool phi_loop = FLAGS_phi_fst_phi_loop,
MatcherRewriteMode rewrite_mode = RewriteMode(FLAGS_phi_fst_rewrite_mode))
: phi_label_(phi_label),
phi_loop_(phi_loop),
rewrite_mode_(rewrite_mode) {}
PhiFstMatcherData(const PhiFstMatcherData &data)
: phi_label_(data.phi_label_),
phi_loop_(data.phi_loop_),
rewrite_mode_(data.rewrite_mode_) {}
static PhiFstMatcherData<Label> *Read(std::istream &istrm,
const FstReadOptions &read) {
auto *data = new PhiFstMatcherData<Label>();
ReadType(istrm, &data->phi_label_);
ReadType(istrm, &data->phi_loop_);
int32 rewrite_mode;
ReadType(istrm, &rewrite_mode);
data->rewrite_mode_ = static_cast<MatcherRewriteMode>(rewrite_mode);
return data;
}
bool Write(std::ostream &ostrm, const FstWriteOptions &opts) const {
WriteType(ostrm, phi_label_);
WriteType(ostrm, phi_loop_);
WriteType(ostrm, static_cast<int32>(rewrite_mode_));
return !ostrm ? false : true;
}
Label PhiLabel() const { return phi_label_; }
bool PhiLoop() const { return phi_loop_; }
MatcherRewriteMode RewriteMode() const { return rewrite_mode_; }
private:
static MatcherRewriteMode RewriteMode(const string &mode) {
if (mode == "auto") return MATCHER_REWRITE_AUTO;
if (mode == "always") return MATCHER_REWRITE_ALWAYS;
if (mode == "never") return MATCHER_REWRITE_NEVER;
LOG(WARNING) << "PhiFst: Unknown rewrite mode: " << mode << ". "
<< "Defaulting to auto.";
return MATCHER_REWRITE_AUTO;
}
Label phi_label_;
bool phi_loop_;
MatcherRewriteMode rewrite_mode_;
};
} // namespace internal
constexpr uint8 kPhiFstMatchInput = 0x01; // Input matcher is PhiMatcher.
constexpr uint8 kPhiFstMatchOutput = 0x02; // Output matcher is PhiMatcher.
template <class M, uint8 flags = kPhiFstMatchInput | kPhiFstMatchOutput>
class PhiFstMatcher : public PhiMatcher<M> {
public:
using FST = typename M::FST;
using Arc = typename M::Arc;
using StateId = typename Arc::StateId;
using Label = typename Arc::Label;
using Weight = typename Arc::Weight;
using MatcherData = internal::PhiFstMatcherData<Label>;
enum : uint8 { kFlags = flags };
// This makes a copy of the FST.
PhiFstMatcher(const FST &fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::make_shared<MatcherData>())
: PhiMatcher<M>(fst, match_type,
PhiLabel(match_type, data ? data->PhiLabel()
: MatcherData().PhiLabel()),
data ? data->PhiLoop() : MatcherData().PhiLoop(),
data ? data->RewriteMode() : MatcherData().RewriteMode()),
data_(data) {}
// This doesn't copy the FST.
PhiFstMatcher(const FST *fst, MatchType match_type,
std::shared_ptr<MatcherData> data = std::make_shared<MatcherData>())
: PhiMatcher<M>(fst, match_type,
PhiLabel(match_type, data ? data->PhiLabel()
: MatcherData().PhiLabel()),
data ? data->PhiLoop() : MatcherData().PhiLoop(),
data ? data->RewriteMode() : MatcherData().RewriteMode()),
data_(data) {}
// This makes a copy of the FST.
PhiFstMatcher(const PhiFstMatcher<M, flags> &matcher, bool safe = false)
: PhiMatcher<M>(matcher, safe), data_(matcher.data_) {}
PhiFstMatcher<M, flags> *Copy(bool safe = false) const override {
return new PhiFstMatcher<M, flags>(*this, safe);
}
const MatcherData *GetData() const { return data_.get(); }
std::shared_ptr<MatcherData> GetSharedData() const { return data_; }
private:
static Label PhiLabel(MatchType match_type, Label label) {
if (match_type == MATCH_INPUT && flags & kPhiFstMatchInput) return label;
if (match_type == MATCH_OUTPUT && flags & kPhiFstMatchOutput) return label;
return kNoLabel;
}
std::shared_ptr<MatcherData> data_;
};
extern const char phi_fst_type[];
extern const char input_phi_fst_type[];
extern const char output_phi_fst_type[];
using StdPhiFst =
MatcherFst<ConstFst<StdArc>, PhiFstMatcher<SortedMatcher<ConstFst<StdArc>>>,
phi_fst_type>;
using LogPhiFst =
MatcherFst<ConstFst<LogArc>, PhiFstMatcher<SortedMatcher<ConstFst<LogArc>>>,
phi_fst_type>;
using Log64PhiFst = MatcherFst<ConstFst<Log64Arc>,
PhiFstMatcher<SortedMatcher<ConstFst<Log64Arc>>>,
input_phi_fst_type>;
using StdInputPhiFst =
MatcherFst<ConstFst<StdArc>, PhiFstMatcher<SortedMatcher<ConstFst<StdArc>>,
kPhiFstMatchInput>,
input_phi_fst_type>;
using LogInputPhiFst =
MatcherFst<ConstFst<LogArc>, PhiFstMatcher<SortedMatcher<ConstFst<LogArc>>,
kPhiFstMatchInput>,
input_phi_fst_type>;
using Log64InputPhiFst = MatcherFst<
ConstFst<Log64Arc>,
PhiFstMatcher<SortedMatcher<ConstFst<Log64Arc>>, kPhiFstMatchInput>,
input_phi_fst_type>;
using StdOutputPhiFst =
MatcherFst<ConstFst<StdArc>, PhiFstMatcher<SortedMatcher<ConstFst<StdArc>>,
kPhiFstMatchOutput>,
output_phi_fst_type>;
using LogOutputPhiFst =
MatcherFst<ConstFst<LogArc>, PhiFstMatcher<SortedMatcher<ConstFst<LogArc>>,
kPhiFstMatchOutput>,
output_phi_fst_type>;
using Log64OutputPhiFst = MatcherFst<
ConstFst<Log64Arc>,
PhiFstMatcher<SortedMatcher<ConstFst<Log64Arc>>, kPhiFstMatchOutput>,
output_phi_fst_type>;
} // namespace fst
#endif // FST_EXTENSIONS_SPECIAL_PHI_FST_H_
| 0 |
coqui_public_repos/STT/tests | coqui_public_repos/STT/tests/test_data/alphabet_windows.txt | a
b
c
| 0 |
coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions | coqui_public_repos/STT/native_client/ctcdecode/third_party/openfst-1.6.7/src/extensions/linear/linear-classifier-fst.cc | // See www.openfst.org for extensive documentation on this weighted
// finite-state transducer library.
#include <fst/extensions/linear/linear-fst.h>
#include <fst/register.h>
using fst::LinearClassifierFst;
using fst::StdArc;
using fst::LogArc;
REGISTER_FST(LinearClassifierFst, StdArc);
REGISTER_FST(LinearClassifierFst, LogArc);
| 0 |
coqui_public_repos/STT | coqui_public_repos/STT/taskcluster/test-python_35_8k-linux-amd64-opt.yml | build:
template_file: test-linux-opt-base.tyml
dependencies:
- "linux-amd64-cpu-opt"
- "test-training_8k-linux-amd64-py36m-opt"
test_model_task: "test-training_8k-linux-amd64-py36m-opt"
args:
tests_cmdline: "${system.homedir.linux}/DeepSpeech/ds/taskcluster/tc-python-tests.sh 3.5.8:m 8k"
workerType: "${docker.dsTests}"
metadata:
name: "DeepSpeech Linux AMD64 CPU Python v3.5 tests (8kHz)"
description: "Testing DeepSpeech for Linux/AMD64 on Python v3.5, CPU only, optimized version (8kHz)"
| 0 |
coqui_public_repos/inference-engine/src | coqui_public_repos/inference-engine/src/ctcdecode/setup.py | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import argparse
import multiprocessing.pool
import os
import platform
import sys
from distutils.command.build import build
from build_archive import *
from setuptools import Extension, distutils, setup
try:
import numpy
try:
numpy_include = numpy.get_include()
except AttributeError:
numpy_include = numpy.get_numpy_include()
except ImportError:
numpy_include = ""
assert "NUMPY_INCLUDE" in os.environ
numpy_include = os.getenv("NUMPY_INCLUDE", numpy_include)
numpy_min_ver = os.getenv("NUMPY_DEP_VERSION", "")
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--num_processes",
default=1,
type=int,
help="Number of cpu processes to build package. (default: %(default)d)",
)
known_args, unknown_args = parser.parse_known_args()
debug = "--debug" in unknown_args
# reconstruct sys.argv to pass to setup below
sys.argv = [sys.argv[0]] + unknown_args
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def maybe_rebuild(srcs, out_name, build_dir):
if not os.path.exists(out_name):
if not os.path.exists(build_dir):
os.makedirs(build_dir)
build_archive(
srcs=srcs,
out_name=out_name,
build_dir=build_dir,
num_parallel=known_args.num_processes,
debug=debug,
)
project_version = read("../../training/coqui_stt_training/VERSION").strip()
build_dir = "temp_build/temp_build"
if sys.platform.startswith("win"):
archive_ext = "lib"
else:
archive_ext = "a"
third_party_build = "third_party.{}".format(archive_ext)
ctc_decoder_build = "first_party.{}".format(archive_ext)
maybe_rebuild(KENLM_FILES, third_party_build, build_dir)
maybe_rebuild(CTC_DECODER_FILES, ctc_decoder_build, build_dir)
decoder_module = Extension(
name="coqui_stt_ctcdecoder._swigwrapper",
sources=["swigwrapper.i"],
swig_opts=["-c++", "-extranative"],
language="c++",
include_dirs=INCLUDES + [numpy_include],
extra_compile_args=ARGS + (DBG_ARGS if debug else OPT_ARGS),
extra_link_args=[ctc_decoder_build, third_party_build],
)
class BuildExtFirst(build):
sub_commands = [
("build_ext", build.has_ext_modules),
("build_py", build.has_pure_modules),
("build_clib", build.has_c_libraries),
("build_scripts", build.has_scripts),
]
setup(
name="coqui_stt_ctcdecoder",
version=project_version,
description="""DS CTC decoder""",
cmdclass={"build": BuildExtFirst},
ext_modules=[decoder_module],
package_dir={"coqui_stt_ctcdecoder": "."},
py_modules=["coqui_stt_ctcdecoder", "coqui_stt_ctcdecoder.swigwrapper"],
install_requires=["numpy%s" % numpy_min_ver],
)
| 0 |